1let flattened = [[0, 1], [2, 3], [4, 5]].reduce(
2 function(accumulator, currentValue) {
3 return accumulator.concat(currentValue)
4 },
5 []
6)
7// flattened is [0, 1, 2, 3, 4, 5]
8
1var objs = [
2 {name: "Peter", age: 35},
3 {name: "John", age: 27},
4 {name: "Jake", age: 28}
5];
6
7objs.reduce(function(accumulator, currentValue) {
8 return accumulator + currentValue.age;
9}, 0); // 35 + 27 + 28 = 90
1// syntax: array.reduce(function, accumulator-initial-value)
2let array = [3, 7, 2, 9, 5]
3const result = array.reduce((accumulator, currentValue, currentIndex, arr) => {
4 // code
5}, initialValue)
6
7// accumulator = will store return value of the function
8// currentValue = iterate through each array element
9// currentIndex = index of currentValue
10// arr = original array
11// initialValue = set accumulator initial value
1Sum array elements:
2let myArr = [1,2,3,-1,-34,0]
3return myArr.reduce((a,b) => a + b,0)
1let newArray = array.reduce( (acc, element, index, originalArray) => {
2 // return acc += element
3}, initialValue)