4

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'
12
  • Why do you want to sort an Object (they are unordered by design)? Can you explain the bigger picture of what you want to do? Commented Mar 23, 2019 at 22:51
  • @JBallin In ES6+, object properties are ordered - it's only in ES5 and before that they have no defined order. Commented Mar 23, 2019 at 22:51
  • Possible duplicate of Sorting JavaScript Object by property value Commented Mar 23, 2019 at 22:55
  • @JBallin I disagree. I feel that the question, asked in 2010, was answered under the premise of ES5 and thus is not ES6 specific. Commented Mar 23, 2019 at 22:59
  • @artomason some answers use ES6. If you truly think it's different, you should edit your title to be ES6 specific. Commented Mar 23, 2019 at 23:01

4 Answers 4

9

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);

Sign up to request clarification or add additional context in comments.

11 Comments

I'm a pretty new to JavaScript, could you break down your answer a little more. there is some syntax that I don't understand. For instance, .sort(([,v1], [,v2]) => and ....
Thank you for the update. I'm still trying to process the information a bit more, but is it possible to sort in descending order (value) using the same method? You talked about keys, but I'm not sure if that applies to value as well.
You sort the pairs using the values, and then you use the pairs to recreate the object in the sorted order. See updated answer (ordered by values descending).
I couldn't get this working properly, but I also noticed that this is actually not what I was looking for, I think lol. I'm looking to sort the Object by JUST the value for question #2. It sounds like I was asking for key and value. I'm not sure if that is how you interpreted it.
It works fine on firefox. Edge doesn't support object spread, so I've replaced it with Object.assign. See update.
|
4

Extract the entries instead of the keys, then sort by the difference of each value:

const unsorted_object = {
    'C': '0003',
    'D': '0004',
    'A': '0001',
    'B': '0002',
    'F': '0005',
};

const sorted_object = {};
Object.entries(unsorted_object)
  .sort((a, b) => a[1] - b[1])
  .forEach(([key, val]) => {
    sorted_object[key] = val;
  });
console.log(sorted_object);

Note that it's probably more appropriate to use reduce to construct an object from an array:

const unsorted_object = {
    'C': '0003',
    'D': '0004',
    'A': '0001',
    'B': '0002',
    'F': '0005',
};

const sorted_object = Object.entries(unsorted_object)
  .sort((a, b) => a[1] - b[1])
  .reduce((a, [key, val]) => {
    a[key] = val;
    return a;
  }, {});
console.log(sorted_object);

Comments

3

You can sort entries and use a reduce() to create new object.

With that said there is likely something wrong in your app design for needing to even do such an operation

const unsorted_object = {
  'C': '0003',
  'D': '0004',
  'A': '0001',
  'B': '0002',
  'F': '0005',
};

const sorted = Object.entries(unsorted_object)
  .sort((a, b) => a[1] - b[1])
  .reduce((a, c) => (a[c[0]] = c[1], a), {})

console.log(sorted)

3 Comments

I'm not sure why this was down voted, some insight would be nice.
@artomason someone went through and downvoted all the initial answers very quickly. It happens...not much can do about it. If you feel it is wrong you have power to upvote
"there is likely something wrong in your app design for needing to even do such an operation" - may I ask why?
0

A cleaner way is to do

Object.entries(unsorted_object)
  .sort()
  .reduce((acc, [k, v]) => ({ ...acc, [k]: v }), {});

This builds up an empty object based on the sorted tuples

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.