Languages
[Edit]
EN

JavaScript - get object properties sorted by value (ES8+)

0 points
Created by:
Geospatial-Palus
630

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 }

 

See also

  1. JavaScript - get object properties sorted by key

References

Alternative titles

  1. JavaScript - sorting object by property value (ES8+)
  2. JavaScript - sort object by value (ES8+)
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
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.

❤️💻 🙂

Join