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; }

Leave a Comment