EN
TypeScript - get sorted object properties by value
0 points
In this article, we would like to show you how to sort object properties by value in TypeScript.
The example shows how to sort obj
object properties by value using Object.entries()
method which returns the object's [key/value] pairs in the same order as a for...in
loop.
Then we sort entries
array with .sort()
method passing arrow function that compares values.
xxxxxxxxxx
1
interface MyObject {
2
a: number;
3
b: number;
4
c: number;
5
}
6
7
const object: MyObject = { b: 2, c: 3, a: 1 };
8
9
const sorted = Object.entries(object).sort((a, b) => a[1] - b[1]);
10
11
console.log(sorted);
Output:
xxxxxxxxxx
1
[ [ 'a', 1 ], [ 'b', 2 ], [ 'c', 3 ] ]
Note:
Above solution is safe because, it behaves like
for ... in
loop with checking condition if an object has a specific own property (likeObject.prototype.hasOwnProperty()
).