TransWikia.com

Combine values from different objects in same array - javascript

Stack Overflow Asked by Thymas1 on December 11, 2021

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!

3 Answers

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)

Answered by Krzysztof Krzeszewski on December 11, 2021

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

Answered by Pedro Lima on December 11, 2021

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()])

Answered by 8HoLoN on December 11, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP