Abdul Hameed
Abdul Hameed

Reputation: 938

Sorting JavaScript Object by property value (Numeric Key)

Hold Down! before marking as duplicate or voting down

let's say I have a java Script Object as below and I wanna to sort this object by values, yes I know array is invented for it and has builtin sort but for some reason I have to go with this object :(

var myObj = {"you": 100, "me": 75,"11111": 20, "foo": 116, "bar": 15};

till now I end up with

{11111: 20, bar: 15, me: 75, you: 100, foo: 116}

but you can see it's not what you want, as in that case, I tried many solution from this deprived solution given here the code is below

Object
 .keys(myObj)
 .sort((a, b) => myObj[a]-myObj[b])
 .reduce((_sortedObj, key) => ({
   ..._sortedObj, 
   [key]: myObj[key]
 }), {}) 

Edit I see this question already it's not my case as I have numeric values so not any single answer given there helpful for me

Upvotes: 1

Views: 517

Answers (2)

adiga
adiga

Reputation: 35263

It is not possible.

In ES2015+, the traversal order of object properties are:

  • First, the keys that are integer indices, in ascending numeric order.
  • Then, all other string keys, in the order in which they were added to the object.
  • Lastly, all symbol keys, in the order in which they were added to the object.

Even if you add the 11111 key at the end, it will always be fetched first when you use Object.keys() or for...in loops

const obj = {};
obj["first"] = 1
obj["second"] = 2
obj["200"] = 200 // integer keys
obj["100"] = 100 

// 100 and 200 property will be moved to the top even if they are added in the end
// 200 was added before 100, but it will be printed after 100 
// because integer indices are traversed in ascending numeric order
console.log(obj) 

// 100 will be the first key
console.log(Object.keys(obj))

You could use use a Map object instead. It has key-value pairs and it remembers the original insertion order of the keys.

Upvotes: 4

SP de Wit
SP de Wit

Reputation: 215

Don't know if this answer could possibly help you:

Sort a dictionary by value in JavaScript

After running the code in that answer on your dictionary I got this:

enter image description here

Is this something you could work with?

Upvotes: 2

Related Questions