How to use reduce () in JavaScript
This article introduces the knowledge of "how to use reduce () in JavaScript". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
1. Definition and usage
The reduce () method takes a function as an accumulator, and each value in the array is reduced from left to right, and is finally evaluated as a value.
Note: reduce () does not execute callback functions for empty arrays.
2. Grammar
Arr.reduce (function (prev, cur, curIndex, arr) {
...
}, init)
3. Parameters
Prev: required, the initial value init, or the return value after each calculation
Cur: required, current element
Index of curIndex:cur
Arr: the array arr to which the current element belongs
Init: the initial value passed to the function.
4. Examples
Var arr = [5, 4, 8, 6, 6, 8, 2, 6, 22, 8, 6]
one
Summation
Sum = arr.reduce (function (prev,cur) {
Console.log (prev, cur)
Return prev + cur
}, 0)
/ / the print result is as follows:
0 5
5 4
9 8
17 6
23 8
31 2
33 6
39 22
61 8
69 6
seventy-five
Find the maximum value of the array item
Max = arr.reduce (function (prev, cur) {
Console.log (prev, cur)
Return Math.max (prev, cur)
}, 0)
/ / the print result is as follows:
0 5
5 4
5 8
8 6
8 8
8 2
8 6
8 22
22 8
22 6
twenty-two
Array deduplication
NewArr = arr.reduce ((prev, cur) = > {
Console.log (prev, cur)
Prev.indexOf (cur) = =-1 & & prev.push (cur)
Return prev
}, [])
/ / the print result is as follows:
[] 5
[5] 4
[5, 4] 8
[5, 4, 8] 6
[5, 4, 8, 6] 8
[5, 4, 8, 6] 2
[5, 4, 8, 6, 2] 6
[5, 4, 8, 6, 2] 22
[5, 4, 8, 6, 2, 22] 8
[5, 4, 8, 6, 2, 22] 6
[5, 4, 8, 6, 2, 22]
Calculate the number of occurrence of string letters
StrNum = str.split ('') .reduce ((strObj, cur) = > {
Console.log (strObj, cur)
StrObj [cur]? StrObj [cur] + +: strObj [cur] = 1
Return strObj
}, {})
/ / the print result is as follows
{}'h'
{h: 1}'e'
{h: 1, e: 1}'l'
{h: 1, e: 1, l: 1}'l'
{h: 1, e: 1, l: 2}'o'
{h: 1, e: 1, l: 2, o: 1}
Convert a two-dimensional array to an one-dimensional array
Var arr1 = [[1jue 2], [1JI 4je 3], [7je 8rem 9]]
Arr2 = arr1.reduce ((xQuery y) = > x.concat (y), [])
/ / [1, 2, 1, 4, 3, 7, 8, 9]
That's all for the content of "how to use reduce () in JavaScript". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!