Computer >> Computer tutorials >  >> Programming >> Javascript

Sort array of objects by string property value in 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.

Therefore, let’s write the code for this function −

Example

The code for this will be −

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

The output in the console will be −

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