I'm trying to sort an array of objects by array of keys. I searched through similar questions but I didn't find anything that could help me
Example:
const data = [
{ label: 'String'},
{ label: 'Number'},
{ label: 'Boolean'},
{ label: 'Array'}
]
const order = [2, 3]
Expected result:
const data = [
{ label: 'Boolean'},
{ label: 'Array'},
{ label: 'String'},
{ label: 'Number'}
]
The problems that I'm facing are
orderarray can have or can not have the same length likedata, the items key that not exists inordermust go to the bottomdataobjects has not an order key to help sort the element, the ordering will made by array object key position
What I tried but not working
data.sort((a, b) => {
const aIndex = data.indexOf(a);
const bIndex = data.indexOf(b);
if(aIndex !== -1) return -1;
if(bIndex !== -1) return 1;
return order.indexOf(aIndex) - order.indexOf(bIndex);
})
[2,3]affect the output? The output you've shown seems to just be alphanumerically sorted.orderarray I store the objects initial position that I want to sort and the new position that I want to put that object . The label string is only an exemple, it can be every text