Sort array of objects by string property value - JavaScript


Suppose, we have an array of Objects like this −

const arr = [
   { first_name: 'Lazslo', last_name: 'Jamf'     },
   { first_name: 'Pig',    last_name: 'Bodine'   },
   { first_name: 'Pirate', last_name: 'Prentice' }
];

We are required to write a JavaScript function that takes in one such array and sort this array according to the alphabetical value of the last_name key.

Example

Following is the code −

const arr = [
   { first_name: 'Lazslo', last_name: 'Jamf' },
   { first_name: 'Pig', last_name: 'Bodine' },
   { first_name: 'Pirate', last_name: 'Prentice' }
];
const sortByLastName = arr => {
   arr.sort((a, b) => {
      return a.last_name.charCodeAt(0) - b.last_name.charCodeAt(0);
   });
};
sortByLastName(arr);
console.log(arr);

Output

This will produce the following output on console −

[
   { first_name: 'Pig', last_name: 'Bodine' },
   { first_name: 'Lazslo', last_name: 'Jamf' },
   { first_name: 'Pirate', last_name: 'Prentice' }
]

Updated on: 01-Oct-2020

239 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements