Home > Back-end >  Combining objects in an array with similar values
Combining objects in an array with similar values

Time:06-14

I've been searching all over the internet for an answer, including picking apart some code that does it correctly, but I can't seem to figure it out.

Basically, I want to take an existing array of objects

rank_data = [
    { name: "IRJBoss", point: 100 },
    { name: "RegainedORU", point: 100 },
    { name: "Kirbycube", point: 100 },
    { name: "RegainedORU", point: 96.735},
    { name: "Kirbycube", point: 96.735 },
    { name: "HanoCrux", point: 93.674 },
    { name: "Rynoxious", point: 93.674 },
    { name: "KanadianKiD", point: 93.674 },
    { name: "RegainedORU", point: 93.674 },
    { name: "LightShade", point: 93.674 },
    ...
]

And format them so all the points are added together, and each name is only used once

rank_data = [
    { name: "RegainedORU", point: 290.409 },
    { name: "Kirbycube", point: 196.735 },
    { name: "IRJBoss", point: 100 },
    { name: "HanoCrux", point: 93.674 },
    { name: "Rynoxious", point: 93.674 },
    { name: "KanadianKiD", point: 93.674 },
    { name: "LightShade", point: 93.674 },
    ...
]

What's the simplest way I could implement this into my code?

CodePudding user response:

Basically you an just group them by name using reduce and then sort by point.

const rank_data = [{"name":"IRJBoss","point":100},{"name":"RegainedORU","point":100},{"name":"Kirbycube","point":100},{"name":"RegainedORU","point":96.735},{"name":"Kirbycube","point":96.735},{"name":"HanoCrux","point":93.674},{"name":"Rynoxious","point":93.674},{"name":"KanadianKiD","point":93.674},{"name":"RegainedORU","point":93.674},{"name":"LightShade","point":93.674}]

const result = Object.values(rank_data.reduce((r, { name, point }) => {
  if (!r[name]) r[name] = { name, point }
  else r[name].point  = point
  return r
}, {})).sort((a, b) => b.point - a.point)

console.log(result)

  • Related