0

i have an array that looks like this:

array = [{game: 1, team: aName, score: 10 },{game: 1, team: bName, score: 1}, {game: 2, team: aName, score: 20}, {game:2, team: bName, score: 30}]

i need a way to sum all the scores from the different teams so i get something like this:

sumArray = [{team:aName, score: 30},{team:bName, score:31}]

is there a way to achieve this with JS?

thanks!

1
  • "javascript group array of objects by property" (+ eventually " site:stackoverflow.com") Commented Jul 23, 2020 at 12:32

3 Answers 3

1

That what you want

const array = [
    { game: 1, team: 'aName', score: 10 },
    { game: 1, team: 'bName', score: 1 },
    { game: 2, team: 'aName', score: 20 },
    { game: 2, team: 'bName', score: 30 }
]

console.log([...array.reduce((a, c) => {
    if (a.has(c.team)) {
        a.get(c.team).score += c.score;
    } else {
        a.set(c.team, c);
    }
    return a;
}, new Map()).values()])

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

4 Comments

the snippet logs an empty object, is that what you wanted?
How does your script work? And you might want to fix the output of the iterator returned by Map.prototype.values()
Great! Thank you!
The result is an array now
0

Yes, there is.

array = [{game: 1, team: 'aName', score: 10 },{game: 1, team: 'bName', score: 1}, {game: 2, team: 'aName', score: 20}, {game:2, team: 'bName', score: 30}];

sumArray = array
    .map(e => e.team) // Map teams
    .filter((v, i, s) => s.indexOf(v) == i) // Getting only unique teams
    .map(t => ({ team: t, score: array.filter(e => e.team == t).reduce((p, v) => p + v.score, 0) })); // generate a reduced object for each team

console.log(sumArray);

Comments

0

Using reduce function to gather the scores

const data = [{
  game: 1,
  team: "aName",
  score: 10
}, {
  game: 1,
  team: "bName",
  score: 1
}, {
  game: 2,
  team: "aName",
  score: 20
}, {
  game: 2,
  team: "bName",
  score: 30
}]

const result = Object.values(data.reduce((result, {team, score}) => {
  if (!result[team]) result[team] = {team, score}
  else result[team].score+=score;
  return result;
}, {}));

console.log(result)

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.