Skip to content

How to Sort an Array of Objects by Property in Javascript

If you need to sort an array of objects by their property values using Javascript, then you don’t need to look further than the built-in sort functionality.

Step 1 – Create an array of objects to work with

let people = [ { name : "John", surname : "Doe", age : 21 }, { name : "Jack", surname : "Bennington", age : 35 }, { name : "Jane", surname : "Doe", age : 19 } ];
Code language: JavaScript (javascript)

Step 2 – Sort by keys

Option 1 – Sort by surname

people.sort((a, b) => a.surname.localeCompare(b.surname)); console.log(people);
Code language: JavaScript (javascript)

This will give you the following output:

[ {name: 'Jack', surname: 'Bennington', age: 35}, {name: 'John', surname: 'Doe', age: 21}, {name: 'Jane', surname: 'Doe', age: 19} ]
Code language: JSON / JSON with Comments (json)

Option 2 – Sort by age

people.sort((a, b) => { return a.age - b.age; }); console.log(people);
Code language: JavaScript (javascript)

This will give you the following output:

[ {name: 'Jane', surname: 'Doe', age: 19}, {name: 'John', surname: 'Doe', age: 21}, {name: 'Jack', surname: 'Bennington', age: 35} ]
Code language: JSON / JSON with Comments (json)

See also  How to Get Longest Word in Sentence in Java
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x