• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

134
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 3 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 3 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 Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error