I have the following array structure
[{
name: "Mobile Uploads"
}, {
name: "Profile Pictures"
}, {
name: "Reports"
}, {
name: "Instagram Photos"
}, {
name: "Facebook"
}, {
name: "My Account"
}, {
name: "Twitter"
}]
I want to reorder the array so that its in the following order: Profile Pictures, Mobile Uploads, Instagram Photos, and the objects afterwards are in alpabetical order.
What you want to do is to make an object that holds the sort exceptions. Then you can write a custom sort() function that accounts for your exceptions.
var list = [{
name: "Date"
}, {
name: "Mobile Uploads"
}, {
name: "Profile Pictures"
}, {
name: "Fig"
}, {
name: "Instagram Photos"
}, {
name: "Cherry"
}, {
name: "Apple"
}, {
name: "Banana"
}];
var exceptions = {
"Profile Pictures": 1,
"Mobile Uploads": 2,
"Instagram Photos": 3
}
list.sort(function(a, b) {
if (exceptions[a.name] && exceptions[b.name]) {
//if both items are exceptions
return exceptions[a.name] - exceptions[b.name];
} else if (exceptions[a.name]) {
//only `a` is in exceptions, sort it to front
return -1;
} else if (exceptions[b.name]) {
//only `b` is in exceptions, sort it to back
return 1;
} else {
//no exceptions to account for, return alphabetic sort
return a.name.localeCompare(b.name);
}
});
console.log(list);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With