JavaScript - get sorted object properties by value

3 points
Created by:
Dirask Community

In this article, we would like to show you how to sort object properties by value in JavaScript.

Practical example:

// ONLINE-RUNNER:browser;

let object = {'b': 2, 'c': 3, 'a': 1};

let sorted = Object.entries(object)
                   .sort((a, b) => a[1] - b[1]);

console.log(sorted);  // a,1,b,2,c,3

Above 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.Ā 


Above solution is safeĀ because, it behaves like for ... in loop with checking conditionĀ if an object has a specific own property (likeĀ Object.prototype.hasOwnProperty()).


See also

Native Advertising
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

ā¤ļøšŸ’» šŸ™‚