-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!

7
  • Have you tried var costs = objects.map(function (obj) { return obj.cost; }) and then sum the costs array's element? Commented Oct 3, 2016 at 10:42
  • You need only iterate the array and sum the cost. Commented Oct 3, 2016 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! Commented Oct 3, 2016 at 10:43
  • Possible duplicate of Sum values from an Array in JavaScript Commented Oct 3, 2016 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. Commented Oct 3, 2016 at 10:48

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.