-4

Hello I'm trying to sort table by score grouped by name so each time i see the name for the first time i see the highest score

var myArray = [
  {name: "Alf", "score": "50"},
  {name: "John", "score": "55"},
  {name: "Alf", "score": "2"},
  {name: "Louise", "score": "10"},
  {name: "Louise", "score": "33"},
  {name: "Alf", "score": "22"}
]

I want to make it look this way

[
  {name: "Alf", "score": "50"},
  {name: "Alf", "score": "22"}
  {name: "Alf", "score": "2"},
  {name: "John", "score": "55"},
  {name: "Louise", "score": "33"},
  {name: "Louise", "score": "10"},
]

How can I do that please

1 Answers1

0

You can use Array#reduce with an object to group all the objects with the same name in an array, sort each array by score, and then flatten them together into one.

var myArray = [
  {name: "Alf", "score": "50"},
  {name: "John", "score": "55"},
  {name: "Alf", "score": "2"},
  {name: "Louise", "score": "10"},
  {name: "Louise", "score": "33"},
  {name: "Alf", "score": "22"}
];
const res = Object.values(myArray.reduce((acc, curr)=>{
  (acc[curr.name] ??= []).push(curr);
  return acc;
}, {})).flatMap(x => x.sort((a,b)=>b.score - a.score));
console.log(res);
Unmitigated
  • 76,500
  • 11
  • 62
  • 80