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
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]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With