0

Sorting by key doesn't work if it has "0"

const resObj = { '15': 686, '03': 598, '14': 803, '16': 1000, "04": 123 };
const resData = Object.entries(resObj).sort(([a,], [b,]) => a - b)
                      .reduce((o, [k, v]) => ({...o, [k]: v}), {})

output:

{ '14': 803, '15': 686, '16': 1000, '03': 598, '04': 123 }

And when "0" is not in the key, it will work

const resObj = { '15': 686, '13': 598, '14': 803, '16': 1000, '17': 123 };

output:

{ '13': 598, '14': 803, '15': 686, '16': 1000, '17': 123 }

Could someone please explain why it become that way

huybean
  • 11
  • 1
  • At least in client-side JS in the browser, this does not appear to reproduce: https://jsfiddle.net/526cvte7/ (tested in Chromium-based browser) – CBroe Oct 18 '22 at 09:03
  • @CBroe it will be reproducible if you loop through keys of the object. – adiga Oct 18 '22 at 09:08
  • 1
    You can't sort the keys of the object keys with integer indices (A number which looks like an array index). `03` is considered as a non-numerical key. – adiga Oct 18 '22 at 09:09
  • const resObj = [{ '15': 686, '03': 598, '14': 803, '16': 1000, "04": 123 }]; function CompareKey(a, b) { return a - b; } resObj.sort(CompareKey); console.log(resObj); – Syed Arsalan Hussain Oct 18 '22 at 09:10
  • Moreover, if the keys are correct representations of integers (unsigned 32 bit range), they are already sorted. No need to call sort. You cannot change that sort order anyway. – trincot Oct 18 '22 at 09:10

0 Answers0