Sort array based on presence of fields in objects JavaScript


Let’s say we have the following array of objects −

const people = [{
   firstName: 'Ram',
   id: 301
}, {
   firstName: 'Shyam',
   lastName: 'Singh',
   id: 1016
}, {
   firstName: 'Dinesh',
   lastName: 'Lamba',
   id: 231
}, {
   id: 341
}, {
   firstName: 'Karan',
   lastName: 'Malhotra',
   id: 441
}, {
   id: 8881
}, {
   firstName: 'Vivek',
   id: 301
}];

We are required to sort this array so that the object with both firstName and lastName property appears first then the objects with firstName or lastName and lastly the objects with neither firstName nor lastName.

So, the code for this will be −

Example

const people = [{
   firstName: 'Ram',
   id: 301
}, {
   firstName: 'Shyam',
   lastName: 'Singh',
   id: 1016
}, {
   firstName: 'Dinesh',
   lastName: 'Lamba',
   id: 231
}, {
   id: 341
}, {
   firstName: 'Karan',
   lastName: 'Malhotra',
   id: 441
}, {
   id: 8881
}, {
   firstName: 'Vivek',
   id: 301
}];
   const sorter = (a, b) => {
      if(a.firstName && a.lastName){
         return -1;
         }else if(b.firstName || b.lastName){
            return 1;
      }else{
         return -1;
   };
};
people.sort(sorter);
console.log(people);

Output

The output in the console will be −

[
   { firstName: 'Karan', lastName: 'Malhotra', id: 441 },
   { firstName: 'Dinesh', lastName: 'Lamba', id: 231 },
   { firstName: 'Shyam', lastName: 'Singh', id: 1016 },
   { firstName: 'Ram', id: 301 },
   { firstName: 'Vivek', id: 301 },
   { id: 8881 },
   { id: 341 }
]

Updated on: 20-Aug-2020

200 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements