using reduce to total array code example
Example 1: how to flatten array with reduce in javascript
let flattened = [[0, 1], [2, 3], [4, 5]].reduce(
function(accumulator, currentValue) {
return accumulator.concat(currentValue)
},
[]
)
// flattened is [0, 1, 2, 3, 4, 5]
Example 2: javascript reduce sum
let nums = [1, 2, 3];
nums.reduce((curr, next) => curr + next);
Example 3: reduce javascript
//note idx and sourceArray are optional
const sum = array.reduce((accumulator, element[, idx[, sourceArray]]) => {
//arbitrary example of why idx might be needed
return accumulator + idx * 2 + element
}, 0);