0

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?

Dres
  • 1,449
  • 3
  • 18
  • 35
  • 2
    `map` isn't appropriate for this job, because it looks at items one at a time, without passing any data between them. `forEach` could do it, but you'd need to use an extra variable outside. [`reduce`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce) is the most appropriate method to use for this. – Jules Jul 18 '18 at 20:37

1 Answers1

1

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 function Array.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);
Community
  • 1
  • 1
Ele
  • 33,468
  • 7
  • 37
  • 75
  • FWIW, I wouldn't use the destructuring syntax because it glosses over that abomination of an input structure that is an array of arrays where each inner array only contains a single object. Any time a data structure looks like that someone has done something wrong on their design. – Alnitak Jul 18 '18 at 21:30