-2

I have the following object:

{1234: "3.05", 1235: "2.03", 1236: "3.05"}

I would like to sort them by value to get something like this:

{1235: "2.03", 1234: "3.05", 1236: "3.05"}

I tried:

const sortedList = _.orderBy(myList, (value, key) => {
        return value;
      }, ['asc']);

The values get sorted but it is only a list of values:

{0: "2.03", 1: "3.05", 2: "3.05"}

How can I retain the keys?

wwjdm
  • 2,178
  • 6
  • 27
  • 51
  • 6
    You cannot sort an object. – Get Off My Lawn Jun 26 '19 at 20:13
  • 2
    "Sorting" the keys of an object doesn't make much sense; it's very fragile. If you just want it for presentation you can always sort the object entries however you want with `Object.entries(yourObject).sort()`. – Pointy Jun 26 '19 at 20:13
  • 2
    Objects are not guaranteed order so there are better ways of doing this. https://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order Solutions are really based on what your goal is. – epascarello Jun 26 '19 at 20:13
  • 2
    Objects **are** guaranteed order, and therefore you **can** sort an object. *But*, you can't sort **this** object because it has integer indices. – Tyler Roper Jun 26 '19 at 20:14
  • 1
    numerical keys are sorted by value, if they could be array indices. – Nina Scholz Jun 26 '19 at 20:14
  • 3
    @TylerRoper that's true, and I think it's good that the committee standardized the behavior, but I would still strongly recommend to anyone against building application code that relies on property order to determine behavior. It's just a huge bug magnet. – Pointy Jun 26 '19 at 20:15
  • 2
    @Pointy I don't disagree with you there. I wouldn't suggest using an object for anything you need ordered. I just think that it's important to dispel the now-untrue notion that objects *cannot* be sorted. **To OP:** Long story short, you can't accomplish what you're looking for using a simple object, nor should you try. Throwing "should or shouldn't" out the window, if an object has integer keys (as yours does), they will **always** be sorted ascending. If order is important, consider a `Map`, or even an array of key-value pairs. – Tyler Roper Jun 26 '19 at 20:16
  • one way to sort object and use its keys is by using Object.entries and sorting values - Object.entries(obj).sort((a,b) => a[1] - b[1]) ... https://codepen.io/nagasai/pen/OexwQY , As mentioned in above comments sorting object is not possible,and order is not guaranteed – Naga Sai A Jun 26 '19 at 20:32

1 Answers1

1

Yes, you can. The only catch is that the output has to be an array in order to guarantee the order of keys.

const input = {1234: "3.05", 1235: "2.03", 1236: "3.05"}

const output = Object.entries(input)
                     .sort(([, v1], [, v2]) => v1 - v2)
                     .map(([key, value]) => ({ [key]: value }))

console.log(output)
Avin Kavish
  • 5,862
  • 1
  • 13
  • 27