1. Syntax
(callback,[initialValue])
reduce executes the callback function in sequence for each element in the array, excluding elements in the array that have been deleted or have never been assigned, and accepts four parameters: the initial value (or the return value of the last callback function), the current element value, the current index, and the array that calls reduce.
callback (Executes a function for each value in the array, containing four parameters)
1. PreviousValue (the value returned by the last callback, or the initial value provided (initialValue))
2. CurrentValue (the currently processed element in the array)
3. index (the index of the current element in the array)
4. array (array that calls reduce)
initialValue (as the first parameter to callback for the first time.) If no initialValue is provided, reduce will execute the callback method from the place where index 1, skipping the first index. If initialValue is provided, start with index 0.
2. Simple usage of reduce
var arr = [1, 2, 3, 4]; var sum = ((x,y)=>x+y) var mul = ((x,y)=>x*y) ( sum ); //Sum, 10( mul ); //Find multiplication product,24
1) Calculate the number of occurrences of each element in the array
let names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice']; let nameNum = ((pre,cur)=>{ if(cur in pre){ pre[cur]++ }else{ pre[cur] = 1 } return pre },{}) (nameNum); //{Alice: 2, Bob: 1, Tiff: 1, Bruce: 1}
2) Deduplication of array
let arr = [1,2,3,4,4,1] let newArr = ((pre,cur)=>{ if(!(cur)){ return (cur) }else{ return pre } },[]) (newArr);// [1, 2, 3, 4]
3) Convert a two-dimensional array into one-dimensional
let arr = [[0, 1], [2, 3], [4, 5]] let newArr = ((pre,cur)=>{ return (cur) },[]) (newArr); // [0, 1, 2, 3, 4, 5]
4) Convert multi-dimensional arrays into one-dimensional
let arr = [[0, 1], [2, 3], [4,[5,6,7]]] const newArr = function(arr){ return ((pre,cur)=>((cur)?newArr(cur):cur),[]) } (newArr(arr)); //[0, 1, 2, 3, 4, 5, 6, 7]
5) Summarize the properties in the object
var result = [ { subject: 'math', score: 10 }, { subject: 'chinese', score: 20 }, { subject: 'english', score: 30 } ]; var sum = (function(prev, cur) { return + prev; }, 0); (sum) //60
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.