I have been working on sorting an array of objects by comparing it with another object. The goal is to display the selected
objects at the top and the rest below them.
While I am currently achieving the desired output, I am interested in exploring ways to further optimize the process.
let myArray = [
{ Name: 'Name 1', id: 1111 },
{ Name: 'Name 2', id: 2222 },
{ Name: 'Name 3', id: 3333 },
{ Name: 'Name 4', id: 4444 },
{ Name: 'Name 5', id: 5555 },
{ Name: 'Name 6', id: 6666 }]
let selected = { 1111: 'some value 1', 4444: 'some value 2' }
sortBySelected = (data) => {
var keys = Object.keys(selected);
return data.filter((obj) => {
if (keys.find((key) => {
return key === String(obj.id);
})) {
return true;
}
return false;
});
}
sortByNotSelected = (data) => {
var keys = Object.keys(selected);
return data.filter((obj) => {
if (keys.find((key) => {
return key === String(obj.id);
})) {
return false;
}
return true;
});
}
sort = (data) => {
data1 = sortBySelected(data);
data2 = sortByNotSelected(data);
return data1.concat(data2);
}
console.log(sort(myArray));