I was wondering how I can sort an array on a custom order, not alphabetical. Imagine you have this array/object:
var somethingToSort = [{
type: \"fruit\"
Try this:
var sortOrder = ['fruit','candy','vegetable']; // Declare a array that defines the order of the elements to be sorted.
somethingToSort.sort(
function(a, b){ // Pass a function to the sort that takes 2 elements to compare
if(a.type == b.type){ // If the elements both have the same `type`,
return a.name.localeCompare(b.name); // Compare the elements by `name`.
}else{ // Otherwise,
return sortOrder.indexOf(a.type) - sortOrder.indexOf(b.type); // Substract indexes, If element `a` comes first in the array, the returned value will be negative, resulting in it being sorted before `b`, and vice versa.
}
}
);
Also, your object declaration is incorrect. Instead of:
{
type = "fruit",
name = "banana"
}, // etc
Use:
{
type: "fruit",
name: "banana"
}, // etc
So, replace the = signs with :'s.