Sort array of objects by single or multiple keys in JavaScript
In TypeScript or JavaScript, sorting an array of objects is made easy in ES6/ES2015.
Given an array of objects named people
, sort them based on different criteria.
1const people = [
2 {
3 "id": 5,
4 "firstName": "Buzz",
5 "lastName": "Lightyear2"
6 },
7 {
8 "id": 2,
9 "firstName": "Buzz",
10 "lastName": "Lightyear"
11 },
12 {
13 "id": 1,
14 "firstName": "Woody",
15 "lastName": "Pride"
16 },
17 {
18 "id": 3,
19 "firstName": "Potato",
20 "lastName": "Head"
21 },
22 {
23 "id": 4,
24 "firstName": "Slinky",
25 "lastName": "Dog"
26 }
27];
Sorting an array of objects by a single key
Sort ascending by number
1// sort ascending by id
2people.sort((a, b) => a.id - b.id)
Sort ascending by string
1// sort ascending by firstName
2people.sort((a, b) => a.firstName.localeCompare(b.firstName))
Sort descending by number
1// sort descending by id
2people.sort((a, b) => b.id - a.id)
Sort descending by string
1// sort descending by firstName
2people.sort((a, b) => b.firstName.localeCompare(a.firstName))
Sorting array of objects by multiple keys
If a secondary key is needed for additional sorting, the same sort
method can be used.
1people.sort(
2 (a, b) => a.firstName.localeCompare(b.firstName) ||
3 a.lastName.localeCompare(b.lastName)
4);
the or logical operator ||
chains multiple sort options.