I'm trying to sum values from an array. I have an array of arrays.
let exampleArray =[[[['1','2'],'3'],'4'],'5'];
I need the sum of all the values using reducer
or map
CodePudding user response:
You first have to flatten array and then you can use reduce
to get sum as:
let exampleArray = [[[['1', '2'], '3'], '4'], '5'];
const result = exampleArray
.flat(Infinity)
.reduce((acc, curr) => curr acc, 0);
console.log(result);
You can also use recursion here as:
let exampleArray = [[[['1', '2'], '3'], '4'], '5'];
function getTotal(arr) {
return !Array.isArray(arr[0])
? arr[0] arr[1]
: getTotal(arr[0]) arr[1];
}
getTotal(exampleArray);
CodePudding user response:
const red = array => {
return array.reduce((sum, current) => {
if (Array.isArray(current)) {
return sum red(current)
}
return sum current
}, 0)
}
red([[['1','2'],'3'],'4'],'5'])