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
You could use .map()
along with .forEach()
function.
var dataSheet = [ [{price: 200}, {price: 200}, {price: 200}], [{price: 200}, {price: 200}], [{price: 200}], ] const res = dataSheet.map(arr => { let sum = 0; arr.forEach(obj => sum += obj.price); return [sum]; }); console.log(res);
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]]
I guess map
+ reduce
is what you are looking for:)
const res = dataSheet.map(el => el.reduce((acc, curr) => acc + curr.price, 0));
Or flatMap
if you need result as [600, 400, 200]:
const res = dataSheet.flatMap(el => el.reduce((acc, curr) => acc + curr.price, 0));
Use map
, reduce
and destructuring.
var dataSheet = [ [{ price: 200 }, { price: 200 }, { price: 200 }], [{ price: 200 }, { price: 200 }], [{ price: 200 }], ]; const result = dataSheet.map((arr) => Object.values( arr.reduce(({ price: acc }, { price }) => ({ price: acc + price })) ) ); console.log(result)
var dataSheet = [ [{price: 200}, {price: 200}, {price: 200}], [{price: 200}, {price: 200}], [{price: 200}], ]; var res = dataSheet.reduce((result, row) => result.concat([[row.reduce((sum, element) => sum + element.price, 0)]]), []); console.log(res);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.