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:
[{id:2, name:"Alexa"},{id:4, name:"Peter"},{id:5, name:"Mary"} ]
I thank you very much for your attention.
CodePudding user response:
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);