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.
To define custom sort function, you need to compare first value with second value. If first value is greater than the second value, return -1. If first value is less than the second value, return 1 otherwise return 0. The above process will sort the data in descending order.
To sort an array of objects, you use the sort() method and provide a comparison function that determines the order of objects.
Example 1: Sort Array by Property NameThe sort() method sorts its elements according to the values returned by a custom sort function ( compareName in this case). Here, The property names are changed to uppercase using the toUpperCase() method. If comparing two names results in 1, then their order is changed.
Sorting array of objectsArrays of objects can be sorted by comparing the value of one of their properties.
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; }
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