0

It should be a simple task but I'm having a little bit of trouble
doing it.

I have the following object:

{
  "chatRoom": [
    {
      "_count": {
        "publicMessages": 10
      }
    },
    {
      "_count": {
        "publicMessages": 10
      }
    },
    {
      "_count": {
        "publicMessages": 10
      }
    }
  ],
}

I would like to get the total sum of every value
inside "publicMessages"
The desidered output:

{
  "totalMessages": 30
}
Diego Braga
  • 161
  • 11
  • Does this answer your question? [How to find the sum of an array of numbers](https://stackoverflow.com/questions/1230233/how-to-find-the-sum-of-an-array-of-numbers) – Lain Mar 14 '22 at 15:40

3 Answers3

4

You can use the Array.reduce() function. If that object is inside a variable named obj, you can achieve this by using:

const result = {
  totalMessages: obj.chatRoom.reduce((acc, cur) => acc + cur._count.publicMessages, 0)
};
moonstar-x
  • 163
  • 7
1

Array.reduce() is the solution, you can run it like this:

const obj={chatRoom:[{_count:{publicMessages:10}},{_count:{publicMessages:10}},{_count:{publicMessages:10}}]};

let sum = obj.chatRoom.reduce( (acc, curr)=>{ return acc+=curr._count.publicMessages??0},0);

console.log(sum);
Andy
  • 61,948
  • 13
  • 68
  • 95
Devesh
  • 603
  • 2
  • 11
  • This code does not work in your snippet. – Andy Mar 14 '22 at 16:02
  • 1
    Right, I just shared a direction to think into, Actual solution will require defining obj and transform sum into expected obj structure – Devesh Mar 14 '22 at 16:11
1

If you want something a little more verbose and understandable than reduce, a simple for/of loop might help you.

const data={chatRoom:[{_count:{publicMessages:10}},{_count:{publicMessages:10}},{_count:{publicMessages:10}}]};

// Initialise the total
let totalMessages = 0;

// Loop over the chatRoom array of objects
// and add the publicMessages value to the total
for (const obj of data.chatRoom) {
  totalMessages += obj._count.publicMessages;
}

// Log the total
console.log({ totalMessages });
Andy
  • 61,948
  • 13
  • 68
  • 95
  • Thank you. your answer works well it's problably more performatic as well. but I like fuctional programming and es6 more. – Diego Braga Mar 14 '22 at 16:15
  • 1
    That's great, and `reduce` is very useful for summing values up. But we see a lot overuse of `reduce` (and one-liners) for code that isn't necessary on this site (I've fallen into that trap :)). Sometimes a simple for/loop is easier to review and debug, particularly if you're working in a team. Happy coding @DiegoBraga. – Andy Mar 14 '22 at 16:29