So let's say I have some data.
const cart = [
[{name: "Jose", total: 5}],
[{name: "Rich", total: 10}]
]
How do I total up those totals using map or forEach?
So let's say I have some data.
const cart = [
[{name: "Jose", total: 5}],
[{name: "Rich", total: 10}]
]
How do I total up those totals using map or forEach?
How do I total up those totals using map or forEach?
The function
Array.map()
is to create new arrays applying a specific handler to each element. On the other hand, the functionArray.forEach()
could be a good approach to loop and sum the values.
The best approach is using the function reduce
.
Assuming that sample always has an array with one index.
const cart = [[{name: "Jose", total: 5}],[{name: "Rich", total: 10}]],
total = cart.reduce((a, [{total} = [obj]]) => a + total, 0);
console.log(total);