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
}
1

3 Answers 3

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)
};
Sign up to request clarification or add additional context in comments.

Comments

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);

2 Comments

This code does not work in your snippet.
Right, I just shared a direction to think into, Actual solution will require defining obj and transform sum into expected obj structure
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 });

2 Comments

Thank you. your answer works well it's problably more performatic as well. but I like fuctional programming and es6 more.
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.

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.