-3

I'd like to sum the values of multiple objects.

I have an array of example 3 items, this varies and can be any number.

_items: 
0: {...}
1: {...}
2: {...}

Each of these item then has the following data:

0: 
dayOfYear: 357
dayOfWeek: 4
noOfUnits: "11"
_id: "12345"
_owner: "12345"
_createdDate: "Thu Dec 23 2021"
year: 2021
_updatedDate: "Thu Dec 23 2021"
week: 51
userId: "12345"
type: "Type 1"

I'd like to add the values of the noOfUnits variable. So for example in item 0 value is 11, item 1 is 2 and item 2 is 5. The total would become 18. This is not limited to 3 items but varies according to the number of items pulled from a database.

Thanks and happy holidays!

1 Answers1

0

You can reduce it

        const results = [
            {noOfUnits: "11"},
            {noOfUnits: "2"},
            {noOfUnits: "5"},
        ]
        console.log(results.reduce((acc, curr) => acc + Number(curr.noOfUnits), 0))

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

Uzair Ashraf
  • 1,171
  • 8
  • 20
  • 1
    I downvoted because this is a very common question. Rather than create multiple low quality questions, it's preferred that we close duplicate questions and consolidate them into a single question. Such questions should not be answered until they are proven not to be a duplicate. – Isaac Corbrey Dec 23 '21 at 20:09
  • Or we can just help people when they ask for it, but opinions can differ I guess – Uzair Ashraf Dec 23 '21 at 20:11
  • 1
    Unfortunately, [it's not just my opinion](https://meta.stackexchange.com/questions/10841/how-should-duplicate-questions-be-handled). The Stack Exchange network is a **Q&A** site, not a forum or help site. As such, if a question already exists then it should be consolidated so that a single source of truth exists. – Isaac Corbrey Dec 23 '21 at 20:13
  • @skara9 https://gfycat.com/enragedlightcoelacanth – Uzair Ashraf Dec 23 '21 at 20:18
  • 1
    @skara9 the point is that we should not be encouraging people to answer questions that are obvious candidates for duplication. I get that people are trying to help OP, but there are a plethora of questions that would solve their problem. People should prioritize guiding askers towards those master questions rather than fragmenting knowledge. – Isaac Corbrey Dec 23 '21 at 20:38