Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Calculator

0

52
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.

7 months 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);

7 months 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 job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2023 PeakU Inc. All Rights Reserved.