Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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' }
]Advertisements