Notifications
Clear all

Sort Array of Objects in JavaScript  

   RSS

2

I have an object array as below and I want to sort it by the lastName property, I know it can be done using the sort function with string or integer array but how do I sort an object array?

var emps = [{ firstName:'Manish', lastName:'Pandey'},
{ firstName:'Deepak', lastName:'Chahar'},
{ firstName:'Virat', lastName:'Kohli' }
];
1 Answer
1

For modern browsers i.e; ES6/ES2015 or later you can do this way:

emps.sort((a, b) => a.lastName.localeCompare(b.lastName));

Prior to ES6/ES2015

emps.sort(function(a, b) {
return a.lastName.localeCompare(b.lastName)
});
This post was modified 7 months ago by Raja
Share:
Share this
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •