Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort an object array by custom order

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.

like image 934
newb1849 Avatar asked Apr 25 '18 17:04

newb1849


People also ask

How do you sort a custom array?

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.

How do you reorder an array of objects?

To sort an array of objects, you use the sort() method and provide a comparison function that determines the order of objects.

How do you sort an array of objects based on a property?

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.

Can we sort array of objects?

Sorting array of objectsArrays of objects can be sorted by comparing the value of one of their properties.


2 Answers

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; }
like image 67
Ele Avatar answered Oct 03 '22 10:10

Ele


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; }
like image 28
Nina Scholz Avatar answered Oct 03 '22 08:10

Nina Scholz