Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sum nested array

Tags:

javascript

I have an array like this

var dataSheet = [
    [{price: 200}, {price: 200}, {price: 200}],
    [{price: 200}, {price: 200}],
    [{price: 200}],
]

I would like to sum all the price and a result like this

result = [[600], [400], [200]]

Any help would be appreciated, thanks

like image 327
Encang Cutbray Avatar asked Aug 22 '26 06:08

Encang Cutbray


1 Answers

Principle is the same for both nested and flat arrays: just use reduce to get sum of values in array. In your case you just need to apply this mechanism to each nested array in your dataSheet and receive new array of values. Method map is designed exactly creating new array based on values from the source array.

So the correct answer would be to use combination of map and reduce.

var dataSheet = [
    [{price: 200}, {price: 200}, {price: 200}],
    [{price: 200}, {price: 200}],
    [{price: 200}],
]

var result = dataSheet.map(data => data.reduce((acc, obj) => acc += obj.price,0));
console.log(result); // [600, 400, 200]

If you really need to have result like [[600],[400],[200]] (embedded arrays instead of just values, you just need to wrap returned values in [], like this:

var dataSheet = [
    [{price: 200}, {price: 200}, {price: 200}],
    [{price: 200}, {price: 200}],
    [{price: 200}],
]

var result = dataSheet.map(data => [data.reduce((acc, obj) => acc += obj.price,0)]);
console.log(result); // [[600], [400], [200]]
like image 132
Artem Arkhipov Avatar answered Aug 23 '26 21:08

Artem Arkhipov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!