doowb / sort-object

Sort the keys in an object.
MIT License
37 stars 6 forks source link

Does not work if object keys are floating numbers! #14

Open rahil471 opened 6 years ago

rahil471 commented 6 years ago
var sortObj = require('sort-object');

console.log(sortObj({a: 1, c: 2, b: 3}));
// --> { a: 1, b: 3, c: 2 }
console.log(sortObj({6: 1, 1: 2, 3: 3}));
// -->{ '1': 2, '3': 3, '6': 1 }
console.log(sortObj({'6.01': 1, '6': 2, '5.55': 3}));
// --> { '6': 2, '5.55': 3, '6.01': 1 }
console.log(sortObj({55.07: 1, 56.00: 2, 55.00: 3, 55.00: 3, 101.10: 8}));
// -> { '55': 3, '56': 2, '101.1': 8, '55.07': 1 } WRONG
console.log(sortObj({'55.07': 1, '56.00': 2, '55.00': 3, '55.00': 3, '101.10': 8}));
// --> { '101.10': 8, '55.00': 3, '55.07': 1, '56.00': 2 }

This outputs the below results..

doowb commented 6 years ago

Thanks for the detailed example. I think the 3rd line is also wrong, but the last line looks correct because the numbers will be sorted as strings.

Would you be able to do a PR with a fix and/or add these examples as tests? If not, I'll try to look into it soon.

doowb commented 6 years ago

@rahil471 I was trying some things out and I'm not able to get the keys to return properly sorted. This must be an internal JavaScript issue since JavaScript doesn't guarantee object keys will be in the same order that you add them to an object. I even went back to node 0.12.8 to see if there was an older version where this worked.

What I think is odd is that it only fails on floating point numbers (or strings that look like floating point numbers).

I'll leave this opened and update the documentation with information on this case.

jonschlinkert commented 6 years ago

I don't think it's just floating point numbers. I think it's a natural sorting issue.

doowb commented 6 years ago

That's what I was thinking at first, but at this line in the code the keys are sorted correctly. It's when adding them to the object (or when doing console.log on the newly returned object) is when they aren't sorted anymore.

rahil471 commented 6 years ago

Exactly that's what I noticed when I was debugging... When the object is reconstructed it rearranges itself in it's natural order. So changing the return line to a-b in sort-asc and b-a in sort-desc won't work either.

I was aware that JavaScript does not guarantee order of the keys, but here somehow we are able to achieve that for object keys as strings or integers.

jonschlinkert commented 6 years ago

That's what I was thinking at first, but at this line in the code the keys are sorted correctly. It's when adding them to the object (or when doing console.log on the newly returned object) is when they aren't sorted anymore.

That means it's not a natural sorting issue?

doowb commented 6 years ago

At least not in this library.