I have an array of objects which have a property called 'CODE'.
[
{
ID: 168,
NAME: "First name",
CODE: "AD"
},
{
ID: 167,
NAME: "Second name",
CODE: "CC"
},
{
ID: 169,
NAME: "Third name",
CODE: "CCM"
},
{
ID: 170,
NAME: "Fourth name",
CODE: "CR"
},
]
How do I order the array by a customized order like:
var item_order = ["CCM","CR","AD","CC"];
Been trying various methods with no success. Please help.
You're going to use
array.sort(customSort)
, where:For huge arrays, I suggest to use an object for the indices.
You can use the function
sort
along with the functionindexOf
.If you have to do something like this often, you might write a small utility to help:
The
order
object is much like what Nina Scholz suggested. The reason foridx + 1
rather than justidx
is to simplify the next line. That line usesInfinity
as a way to sort to the end those whose key value is either undefined or not in the sort list. If you want them at the beginning, you can use0
or-Infinity
.