0

I want to sort following object by Value

var myObj = {"1": {"Value": 40}, "2": {"Value": 10}, "3": {"Value": 30}, "4": {"Value": 20}};

I tried to use sort to get keys of desired order but while making new object using it is the problem for me. I tried below method to sort:

var myObj = {"1": {"Value": 40}, "2": {"Value": 10}, "3": {"Value": 30}, "4": {"Value": 20}};
sorted = Object.keys(myObj).sort((a,b) => myObj[a].Value - myObj[b].Value).reduce((_sortedObj, key) => ({
   ..._sortedObj, 
   [key]: myObj[key]
 }), {});
console.log(sorted);

Can somebody point out where am I making mistake?

Rohanil
  • 1,717
  • 5
  • 22
  • 47
  • Object properties have no defined order. If you need order, convert to an array. All browers sort numerical properties by their numerical order irrespective of insertion order. – trincot Jan 05 '18 at 10:14
  • You can't sort object properties. Do you want an array? – Reinstate Monica Cellio Jan 05 '18 at 10:15
  • what is your expected result? In Array form ? Object form ? – Dean Jan 05 '18 at 10:16
  • @Dean: I expect it in object form – Rohanil Jan 05 '18 at 10:16
  • I'd love to provide a possible alternative, but this question has been closed. `Object.keys(myObj).map(function(v){return Object.assign({'Index':v},myObj[v])}).sort(function(a,b){return a.Value>b.Value?1:-1})` yields a sorted array of objects contain index and value properties => ` [{Index: "2", Value: 10}, {Index: "4", Value: 20}, {Index: "3", Value: 30}, {Index: "1", Value: 40}]` – Joshua R. Jan 05 '18 at 10:30

1 Answers1

0

Javascript Objects are not Ordered like arrays. They are key value pairs and you can access any value in constant time by just it's key.

If you want them to be ordered then you can iterate over the properties of your object and push them in array and sort them in the order you want.

you can get something like this.

[{"Value": 10}, {"Value": 20}, {"Value": 30}, {"Value": 40}];

This is an array of Objects where each element is an object containing a key-value pair.

Rohit Agrawal
  • 1,496
  • 9
  • 20