Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a JavaScript object by key or value; ES6

Before I ask; there are a bunch of discussions on this particular subject, most of which pertain to ES5 and do not necessarily hold truth for ES6. I'm attempting to get some clarification, and maybe help the next person that is scouring the internet for an answer. This is in reference to ES6 specifically.

QUESTIONS:

Consider the following object structure:

const unsorted_object = {
    'C': '0003',
    'D': '0004',
    'A': '0001',
    'B': '0002',
    'F': '0005',
}; 
  1. How can I sort a JavaScript object by key? (Answered here)

    const sorted_object = {};
    Object.keys(unsorted_object).sort().forEach(function(key) {
        sorted_object[key] = unsorted_object[key];
    });
    
  2. How can I sort a JavaScript object by the key value?

EDIT #1

I might not have been totally clear on question #2. The idea is to sort the JavaScript object by the value of the key, not by key and value.

EDIT #2

const unsorted_object = {
    '0001': '13.1666',
    '0002': '11.0001',
    '0003': '10.6664',
    '0004': '13.1666',
    '0005': '7.3331',
};

Output:

'0001': '13.1666'
'0004': '13.1666'
'0002': '11.0001'
'0003': '10.6664'
'0005': '7.3331'
like image 356
artomason Avatar asked Oct 15 '25 07:10

artomason


1 Answers

Objects keys in ES6 have a traversal order. Integer keys are always first, and are sorted in an ascending order (0 -> 9). In non integer keys the order of assignment is preserved (see this article). To sort the object's keys we need to recreate the object, and add the keys in the required order.

Note: This means that sorting will only work on non integer keys, because integers are always 1st, and always sorted in an ascending order.

To sort and recreate the object:

  • Use Object.entries() to get an array of key/value pairs - [[key, value], [key, value]]
  • Sort them by the value (the 2nd item in the pair) using array destructuring - [, v1]. Cast the strings to number using the + operator,
  • Reduce back to an object. Take the key and value using destructuring [k , v], and add them to the accumulator object using computed property names - ({ [k]: v }), and object spread - ({ ...r, [k]: v })

const unsorted_object = {
    '0001': '13.1666',
    '0002': '11.0001',
    '0003': '10.6664',
    '0004': '13.1666',
    '0005': '7.3331',
};

const sorted_object = Object.entries(unsorted_object)
  .sort(([,v1], [,v2]) => +v2 - +v1)
  .reduce((r, [k, v]) => ({ ...r, [k]: v }), {});

console.log(sorted_object);

If supported you can create the object from the entries using Object.fromEntries() instead of Array.reduce():

const unsorted_object = {
    '0001': '13.1666',
    '0002': '11.0001',
    '0003': '10.6664',
    '0004': '13.1666',
    '0005': '7.3331',
};

const sorted_object = Object.fromEntries(
  Object.entries(unsorted_object)
    .sort(([,v1], [,v2]) => +v2 - +v1)
);

console.log(sorted_object);

Edge friendly version, that uses Object.assign() instead of spread:

const unsorted_object = {
    '0001': '13.1666',
    '0002': '11.0001',
    '0003': '10.6664',
    '0004': '13.1666',
    '0005': '7.3331',
};

const sorted_object = Object.entries(unsorted_object)
  .sort(([,v1], [,v2]) => +v2 - +v1)
  .reduce((r, [k, v]) => Object.assign(r, { [k]: v }), {});

console.log(sorted_object);
like image 81
Ori Drori Avatar answered Oct 17 '25 21:10

Ori Drori



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!