In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly explains "how to use the reduce () method in JavaScript". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to use the reduce () method in JavaScript".
Syntax arr.reduce (function (prev,cur,index,arr) {...}, init)
Among them
Arr represents the original array
Prev represents the return value of the last callback, or the initial value init
Cur represents the array elements that are currently being processed
Index represents the index of the array element currently being processed. If an init value is provided, the index is 0, otherwise the index is 1
Init represents the initial value.
Doesn't it look complicated? It doesn't matter, it just looks like it, but there are only two commonly used parameters: prev and cur. Next, let's follow the examples to see the specific usage.
II. Examples
First provide a raw array:
Var arr = [3, 9, 4, 4, 3, 6, 0, 9]
There are many ways to achieve the following requirements, including the solution using reduce (), which is relatively simple to implement.
1. Find the sum of array items var sum = arr.reduce (function (prev, cur) {return prev + cur;}, 0)
Since the initial value of 0 is passed in, the value of prev starts with 0 and the value of the first cur of the array is 3. After addition, the return value is 3 as the value of the next callback, and then continues to add to the next array item, and so on, until the sum of all array items is completed and returned.
two。 Find the maximum value of the array item var max = arr.reduce (function (prev,cur) {return Math.max (prev,cur);})
Since no initial value is passed, the value of prev starts with the first item of the array, item 3, and the value of cur, the value of the second item of the array, 9. Take the maximum of two values and proceed to the next round of callbacks.
3. Array var newArr = arr.reduce (function (prev, cur) {prev.indexOf (cur) = =-1 & & prev.push (cur); return prev;}, [])
The basic principles of the implementation are as follows:
① initializes an empty array
② looks for the first item in the array that needs to be reprocessed in the initialization array, and if it cannot be found (certainly not in the empty array), it adds the item to the initialization array
③ looks for the second item of the array that needs to be reprocessed in the initialization array, and if it cannot be found, it continues to add the item to the initialization array
④...
⑤ looks for the nth item of the array that needs to be reprocessed in the initialization array, and if it cannot be found, it continues to add the item to the initialization array
⑥ returns the initialization array
Other related methods 1. ReduceRight ()
The usage of this method is actually the same as that of reduce (), except that it traverses in reverse order, starting from the last item of the array and traversing forward to the first item.
2. ForEach (), map (), every (), some () and filter ()
For details, please stamp → for a brief description of the use of forEach (), map (), every (), some () and filter ().
Key summary:
Reduce () is the merging method of the array, which traverses each item of the array like forEach (), map (), filter () and other iterative methods, but reduce () can simultaneously calculate the result of traversing the previous array items with the current ergodic term, which can not be achieved by other iterative methods.
Let's take a look at W3C grammar first.
Array.reduce (function (total, currentValue, currentIndex, arr), initialValue); / * total: required. The initial value, or the return value after the calculation is finished. CurrentValue: required. Current element. CurrentIndex: optional. Index of the current element; arr: optional. The array object to which the current element belongs. InitialValue: optional. The initial value passed to the function is equivalent to the initial value of total. , /
Common usage
Array summation
Const arr = [12,34,23]; const sum = arr.reduce ((total, num) = > total + num); const arr = [12,34,23]; const sum = arr.reduce ((total, num) = > total + num, 10); / / summation var result = [{subject: 'math', score: 88}, {subject:' chinese', score: 95}, {subject: 'english', score: 80}] Const sum = result.reduce ((accumulator, cur) = > accumulator + cur.score, 0); const sum = result.reduce ((accumulator, cur) = > accumulator + cur.score,-10); / / 10 points deducted from the total score
Array maximum
Const a = [23,123 pre,cur,inde,arr 342 const 12]; const max = a.reduce (function (pre,cur,inde,arr) {return pre > cur?pre:cur;}); / / 342
Advanced usage
Usage in array objects
Const objArr = [{name: 'boss'}, {name: 'second'}, {name: 'third'}]; const res = objArr.reduce ((pre, cur, index, arr) = > {if (index = 0) {return cur.name;} else if (index = (arr.length-1)) {return pre + 'and' + cur.name;} else {return pre +','+ cur.name;}},'')
Find the number of times the letters appear in the string
Const str = 'sfhjasfjgfasjuwqrqadqeiqsajsdaiwqdaklldflas-cmxzmnha';const res = str.split (''). Reduce ((accumulator, cur) = > {accumulator [cur]? Organizer [cur] + +: accumulator [cur] = 1; return accumulator;}, {})
Array to array
Var arr1 = [2,3,4,5,6]; / / the square of each value var newarr = arr1.reduce ((accumulator, cur) = > {accumulator.push (cur * cur); return accumulator;}, [])
Array to object
Var streams = [{name: 'technology', id: 1}, {name: 'design', id: 2}]; var obj = streams.reduce ((accumulator, cur) = > {accumulator [cur.id] = cur; return accumulator;}, {})
Advanced usage
Multidimensional overlay operation
Var result = [{subject: 'math', score: 88}, {subject:' chinese', score: 95}, {subject: 'english', score: 80}]; var dis = {math: 0.5, chinese: 0.3, english: 0.2}; var res = result.reduce ((accumulator, cur) = > dis [cur.subject] * cur.score + accumulator, 0); var prices = [{price: 23}, {price: 45}, {price: 56}] Var rates = {us: '6.5, eu:' 7.5,}; var initialState = {usTotal:0, euTotal: 0}; var res = prices.reduce ((accumulator, cur1) = > Object.keys (rates). Reduce ((prev2, cur2) = > {console.log (accumulator, cur1, prev2, cur2); accumulator [`${cur2} Total`] + = cur1.price * rates [cur2]; return accumulator;}, {}), initialState) Var manageReducers = function () {return function (state, item) {return Object.keys (rates). Reduce ((nextState, key) = > {state [`${key} Total`] + = item.price * rates [key]; return state;}, {});}; var res1= prices.reduce (manageReducers (), initialState)
Flat a two-dimensional array
Var arr = [[1,2,8], [3,4,9], [5,6,10]]; var res = arr.reduce ((x, y) = > x.concat (y), [])
Object array deduplication
Const hash = {}; chatlists = chatlists.reduce ((obj, next: Object) = > {const hashId = `${next.topic} _ ${next.stream_id}`; if (! hash [hashId]) {hash [`${next.topic} _ ${next.stream_id}`] = true; obj.push (next);} return obj;}, [])
Compose function
Redux compose source code implementation
Function compose (... funs) {if (funs.length = 0) {return arg = > arg;} if (funs.length = 1) {return funs [0] } return funs.reduce ((a, b) = > (... arg) = > a (b (.arg)} Thank you for your reading. The above is the content of "how to use the reduce () method in JavaScript". After the study of this article, I believe you have a deeper understanding of how to use the reduce () method in JavaScript, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.