-2

First, I'm asking this from my phone so it is not practical to place a code snippet at this time, however I just need to pointed in the right direction and will be as specific as possible.

I have an array that consists of multiple objects. Each object has a number of properties and values, one of which is "Cost: cost" with the value being a number.

How do I go about finding the sum, getting the total cost of all the objects? I've tried using reduce() but am not getting the proper results.

Any help is much appreciated!

Ritchie
  • 11
  • Have you tried `var costs = objects.map(function (obj) { return obj.cost; })` and then sum the costs array's element? – Jakub Jankowski Oct 03 '16 at 10:42
  • You need only iterate the array and sum the cost. – BrTkCa Oct 03 '16 at 10:43
  • I've not. I was actually advised to use reduce instead of map but I am willing to try it since I was not able to get that to work properly. Thank you! – Ritchie Oct 03 '16 at 10:43
  • Possible duplicate of [Sum values from an Array in JavaScript](http://stackoverflow.com/questions/16057672/sum-values-from-an-array-in-javascript) – BrTkCa Oct 03 '16 at 10:44
  • Lucas, I saw that but decided it was different enough as that post was referencing nested arrays with on numbers and this is referring to an array with multiple objects that have numbers, methods, strings, and Booleans. – Ritchie Oct 03 '16 at 10:48
  • Iterate array or array of objects have many answer and question, a little of search and test you can find what you need. – BrTkCa Oct 03 '16 at 10:52
  • I've traced the issue back to another method that is causing my issue. Thank you all for your time and help. Much appreciated! – Ritchie Oct 03 '16 at 10:56

1 Answers1

0

With reduce:

a.reduce((sum, current) => sum + current.cost, 0)

sum is your accumulator current the current object which is traversed over 0 is the initial value of your accumulator

Scarysize
  • 4,131
  • 25
  • 37