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 can use the function sort
along with the function indexOf
.
var array = [ { 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" }],
item_order = ["CCM","CR","AD","CC"];
array.sort((a, b) => item_order.indexOf(a.CODE) - item_order.indexOf(b.CODE));
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
For huge arrays, I suggest to use an object for the indices.
var array = [{ 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" }],
item_order = ["CCM", "CR", "AD", "CC"],
order = item_order.reduce((r, k, v) => Object.assign(r, { [k]: v }), {});
array.sort((a, b) => order[a.CODE] - order[b.CODE]);
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You're going to use array.sort(customSort)
, where:
function customSort(a,b)
{
a = item_order.indexOf(a.CODE);
b = item_order.indexOf(b.CODE);
return a - b;
}
If you have to do something like this often, you might write a small utility to help:
const array = [{ 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" },{ ID: 166, NAME: "Fifth name", CODE: "CCM" }, { ID: 171, NAME: "Sixth name", CODE: "XXX" }, { ID: 172, NAME: "Seventh name", CODE: "CR" }]
const sortOn = (prop, list) => {
const order = list.reduce((obj, key, idx) => Object.assign(obj, { [key]: idx + 1}), {});
const getVal = item => order[item[prop]] || Infinity
return (a, b) => getVal(a) - getVal(b)
}
array.sort(sortOn('CODE', ["CCM", "CR", "AD", "CC"]))
console.log(array)
The order
object is much like what Nina Scholz suggested. The reason for idx + 1
rather than just idx
is to simplify the next line. That line uses Infinity
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 use 0
or -Infinity
.