Sorting arrays by two criteria in JavaScript


Let the following be the array to be sorted by date and isImportant. All the objects with isImportant property true rank higher than any any of the object with isImportant false and both the groups sorted according to the date property.

Following is our array −

const array = [{
   id: 545,
   date: 591020824000,
   isImportant: false,
},
{
   id: 322,
   date: 591080224000,
   isImportant: false,
},
{
   id: 543,
   bdate: 591080424000,
   isImportant: true,
},
{
   id: 423,
   date: 591080225525,
   isImportant: false,
},
{
   id: 135,
   date: 591020225525,
   isImportant: true,
},
];

After that, we can use the array sort method like this to achieve the desired results on the above array −

array.sort((a, b) => {
   if(a.isImportant && !b.isImportant){
      return -1;
   }else if(!a.isImportant && b.isImportant){
      return 1;
   }else{
      return b.date-a.date;
   }
});

The sort() callback function usually receives two arguments, say a and b, which are nothing but two elements of the array on which sort() was called and the callback function runs for each possible pair of elements of the array.

Returning -1 (any negative value) from the callback means we rank the first element higher than second.

Returning 1 (any positive value) from the callback means we rank the second element higher than first.

Returning 0 makes no changes. We check if any of the a or b has isImportant property set to false, if yes then we rank that one lower. Otherwise, we rank them according to their date property.

Example

Let us now see the complete example −

const array = [{
   id: 545,
   date: 591020824000,
   isImportant: false,
},
{
   id: 322,
   date: 591080224000,
   isImportant: false,
},
{
   id: 543,
   bdate: 591080424000,
   isImportant: true,
},
{
   id: 423,
   date: 591080225525,
   isImportant: false,
},
{
   id: 135,
   date: 591020225525,
   isImportant: true,
},
];
array.sort((a, b) => {
   if(a.isImportant && !b.isImportant){
      return -1;
   }else if(!a.isImportant && b.isImportant){
      return 1;
   }else{
      return b.date-a.date;
   }
});
console.log(array);

Output

The output of the code in the console will be −

[
   { id: 3, date: 591080424000, isImportant: true },{ id: 5, date: 591020225525, isImportant: true },
   { id: 4, date: 591080225525, isImportant: false },{ id: 2, date: 591080224000, isImportant: false },
   { id: 1, date: 591020824000, isImportant: false }
]

Updated on: 18-Aug-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements