Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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"} ]

in this case in the second array the id 3 did not exist, so I continue with the four and the values that are not in the array 1 by default would go to the end of the second array and the same if in the case that they exist in the first array values that are not in the array 2
example:

orderedArray = [1,2,3,4]
arrayToOrder = [{id:2, name:"Alexa"}, {id:5, name:"Mary"},{id:4, name:"Peter"} ]

result:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

I thank you very much for your attention.

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading