EN
JavaScript - get object properties sorted by value (ES8+)
0 points
In this article, we would like to show you how to get object properties sorted by value in JavaScript.
Note:
Object properties are ordered since ES6.
The main concept of this solution is to use:
entries()
method which returns an array of given object entries (key/value pairs),sort()
method to sort the array,reduce()
method to create a new object from the array with sorted properties.
Note:
The
Object.entries()
method was introduced in ES8 (ECMAScript 2017).
xxxxxxxxxx
1
var object = {
2
a: 2,
3
b: 1,
4
c: 3,
5
};
6
7
const sortedObject = Object.entries(object)
8
.sort((a, b) => a[1] - b[1])
9
.reduce((result, entry) => {
10
result[entry[0]] = entry[1];
11
return result;
12
}, {});
13
14
console.log(JSON.stringify(object)); // { a: 2, b: 1, c: 3 }
15
console.log(JSON.stringify(sortedObject)); // { b: 1, a: 2, c: 3 }
Note:
The default sort order is ascending but elements converted into strings are compared by their sequences of UTF-16 code units values.
As an alternative for older web browsers, we use Object.keys()
method to get array of object's keys. In the next step, we sort and map them into a new sorted object.
xxxxxxxxxx
1
var object = {
2
a: 2,
3
b: 1,
4
c: 3,
5
};
6
7
const sortedObject = Object.keys(object)
8
.map(key => [key, object[key]])
9
.sort((a, b) => a[1] - b[1])
10
.reduce((result, entry) => {
11
result[entry[0]] = entry[1];
12
return result;
13
}, {});
14
15
console.log(JSON.stringify(object)); // { a: 2, b: 1, c: 3 }
16
console.log(JSON.stringify(sortedObject)); // { b: 1, a: 2, c: 3 }