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).
Practical example
// ONLINE-RUNNER:browser;
var object = {
a: 2,
b: 1,
c: 3,
};
const sortedObject = Object.entries(object)
.sort((a, b) => a[1] - b[1])
.reduce((result, entry) => {
result[entry[0]] = entry[1];
return result;
}, {});
console.log(JSON.stringify(object)); // { a: 2, b: 1, c: 3 }
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.
Alternative solution for older web browsers
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.
// ONLINE-RUNNER:browser;
var object = {
a: 2,
b: 1,
c: 3,
};
const sortedObject = Object.keys(object)
.map(key => [key, object[key]])
.sort((a, b) => a[1] - b[1])
.reduce((result, entry) => {
result[entry[0]] = entry[1];
return result;
}, {});
console.log(JSON.stringify(object)); // { a: 2, b: 1, c: 3 }
console.log(JSON.stringify(sortedObject)); // { b: 1, a: 2, c: 3 }