0

I have an Object like this:

let arr ={
1.2 : 44,
55: 41,
13: 59,
2.3 : 77
}

console.log(Object.fromEntries(Object.entries(arr).sort()))

//   Result: 
//  {
//    "13": 59,
//    "55": 41,
//    "1.2": 44,
//    "2.3": 77
//  }

//   Expected Result: 
//  {
//    "1.2": 44,
//    "2.3": 77,
//    "13": 59,
//    "55": 41
//  }

The sort function treats keys as string and not floating point numbers.

I've tried Lodash Sort too, but no luck.

Any help would be appreciated.

SalmanShariati
  • 3,681
  • 3
  • 21
  • 42
  • 1
    13 and 55 will always be on top because integer keys are enumerated in ascending order before other keys. – adiga Apr 26 '21 at 09:12
  • 1
    @adiga you're too fast - went to edit in the ES6 ordering dupes and they were already there :D – VLAZ Apr 26 '21 at 09:13
  • 1
    At any rate, that's correct - keys that contain non-negative integers will always be 1. sorted first 2. sorted in order. If order is important *do not rely on object keys*. Use a different structure that defines the order via an array - using objects: `[{id: 1.2, value: 44}, { id: 2.3, value: 77}]` or using an array of pairs `[[1.2, 44], [2.3, 77]]`. The latter can be useful for directly loading into a map: `new Map([[1.2, 44], [2.3, 77]])` will create a map `{ 1.2 → 44, 2.3 → 77 }` and would 1. preserve the type of the keys (they'd be numbers) 2. preserve the insertion order. – VLAZ Apr 26 '21 at 09:17

0 Answers0