Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

213
Views
How to sort an Array based on another Array in JS

if I have an array: [1,2,3,4] and another array of objects:

[{id:2, name:"Alexa"}, {id:1, name:"John"},{id:5 , name:"Mary"},{id:4, name:"Peter"} ], 

how can I make an optimal function to sort based on the first array? result:

[{id:1, name:"John"},{id:2, name:"Alexa"},{id:4, name:"Peter"},{id:5, name:"Mary"} ]

I thank you very much for your attention.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Is this what you need?

const initialArr = [
  { id: 2, name: "Alexa" },
  { id: 1, name: "John" },
  { id: 5, name: "Mary" },
  { id: 9, name: "Zuzu" },
  { id: 3, name: "Mary" },
  { id: 4, name: "Peter" }
];
const arr = [1, 2, 3, 4];

initialArr.sort((a, b) => {
  const getTypeIndex = (x) => arr.indexOf(x.id);

  return getTypeIndex(a) - getTypeIndex(b) && a.id - b.id;
});

console.log(initialArr);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!