0

I want to merge the same id, but it's not as easy as I thought. Can you help me?

const data = [
    {id: 1, stats: {kill:7, de: 3, as: 8}, wins: true},
  {id: 2, stats: {kill:1, de: 3, as: 8}, wins: false},
  {id: 2, stats: {kill:17, de: 9, as: 3}, wins: true},
  {id: 1, stats: {kill:6, de: 2, as: 1}, wins: true},
];

My code until now

 const result = data.reduce((b,c) => ((b[b.findIndex(d => d.id === c.id)] || b[b.push({
      id: c.id,
      stats: c.stats.kill,
      count: 0,
    }) - 1]).count++, b), []);

goal

[
  {id: 1, stats: {kill: 13, de: 5, as: 9}, victoryRate: '100%', count:2},
  {id: 2, stats: {kill: 18, de: 12, as: 11}, victoryRate: '50%', count: 2}
]

If it is difficult to answer, please recommend Keyword so that I can do it myself!

Thanks

6
  • 2
    Please search before posting. More about searching here. Commented Jan 29, 2020 at 7:04
  • 1
    Oh, I'm sorry. I'll search more before I start asking questions. Commented Jan 29, 2020 at 7:41
  • 1
    const resultObj = data.reduce( (obj,val) => { if (obj[val.id]) { obj[val.id].stats.kill = obj[val.id].stats.kill + val.stats.kill; obj[val.id].stats.de = obj[val.id].stats.de + val.stats.de; obj[val.id].stats.as = obj[val.id].stats.as + val.stats.as; obj[val.id].wins = obj[val.id].wins + val.wins; obj[val.id].count = obj[val.id].count + 1; obj[val.id].victoryRate = Math.round( obj[val.id].wins / obj[val.id].count * 100 ) + '%'; } else { obj[val.id] = val; obj[val.id].count = 1; } return obj; }, {}); Commented Jan 29, 2020 at 9:08
  • 1
    const result = Object.values(resultObj); result.forEach(element => { delete element.wins; }); console.log(result); Commented Jan 29, 2020 at 9:32
  • 1
    <script> const data = [ {id: 1, stats: {kill:7, de: 3, as: 8}, wins: true}, {id: 2, stats: {kill:1, de: 3, as: 8}, wins: false}, {id: 2, stats: {kill:17, de: 9, as: 3}, wins: true}, {id: 1, stats: {kill:6, de: 2, as: 1}, wins: true}, ]; ids=[]; data.forEach(function(d) { ids.push(d.id); }); u_ids = ids.filter(function(item, pos) { return ids.indexOf(item) == pos; }) result=[]; for(var i=0;i<u_ids.length;i++){ var kill=0; var win=0; var loss=0; var de=0; var as=0; count=0; Commented Jan 29, 2020 at 9:46

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.