Sort an object array by custom order
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;
}
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"
},
];
var sortOrder = ["CCM","CR","AD","CC"];
var sorted = array.sort((a, b) => sortOrder.indexOf(a.CODE) - sortOrder.indexOf(a.CODE));
console.log(sorted);