0

So I have an array like this:

const age= [
 {
      name: "mike",
      age: 31
}, {
      name: "taylor",
      age: 29
}, {
      name: "liam",
      age: 42
}, {
      name: "harry",
      age: 19
}, {
      name: "louis",
      score: 41
},];

I need to rearrange this so that the names liam and louis will always be on top of the array.

Like this : (order of others doesn't matter) Like :

const age= [
 {
      name: "liam",
      age: 42
}, {
      name: "louis",
      age: 41
}, {
      name: "mike",
      age: 31
}, {
      name: "harry",
      age: 19
}, {
      name: "taylor",
      score: 29
},];
Mina
  • 14,386
  • 3
  • 13
  • 26
  • No need to sort, just collect them to 2 separate arrays and join them. `const names = ["liam", "louis"], a1 = [], a2 = []` Then loop and add them to 2 arrays: `for(const user of age) { if(names.includes(user.name)) a1.push(user) else a2.push(user) }; const output = [...a1, ...a2]` – adiga Nov 04 '22 at 13:51

0 Answers0