4 ms·
Just read the docs: > If `compareFunction` is not supplied, all non-undefined array elements are sorted by converting them to strings and comparing strings in
by ImpressiveWebs 6y ago
Just read the docs:
> If `compareFunction` is not supplied, all non-undefined array elements are sorted by converting them to strings and comparing strings in UTF-16 code units order. For example, "banana" comes before "cherry". In a numeric sort, 9 comes before 80, but because numbers are converted to strings, "80" comes before "9" in the Unicode order.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
- Gaelan 6y ago"it's documented" is no excuse for unexpected behavior. (Relevant xckd: https://xkcd.com/293/ https://xkcd.com/293/)
- asdf-asdf-asdf 6y agounfortunately it's not possible to change the behavior because of backward compatibility. maybe we could have a `sort2()` method that works differently.
- clktmr 6y agoWell, what would be the expected behavior of sorting an untyped array?
- danShumway 6y agoI'm not sure it's unexpected. Javascript has some weird behaviors, but in this case Arrays in Javascript can contain multiple types. How would you sort an array of `['cat', 80.3, '80']`? I think I would expect that to end up as `['80', 80.3, 'cat']`, not `[80.3, '80', 'cat']. Or to make things more complicated, `['cat', 80.3, { foo: 'bar' }, true]`. Do we want to try and intuit whether that object gets converted to a string or a value? Do we base that intuition on the prototype chain, or what? I think it makes sense to cast every object/type in the array to a shared format so everything can be compared based on the same criteria. --- Have simple rules that are universally applied: - All objects are converted to strings - Strings are sorted alphabetically vs something weird like: - We try to intuit what type you want based on several common type conversions and possibly the prototype - We have a set of built-in rules about which primitive types (number, boolean, string, Symbol) comes before and after other primitive types.
- Gaelan 6y agoPersonally, I'd expect sorting non-homogenous arrays to either sort by type first, or (even better, IMO) throw an exception.
- naikrovek 6y ago> I'm not sure it's unexpected. What do YOU expect when you ask someone to sort items that are clearly numbers? I don't know about you, but I do not expect what actually happened.
- danShumway 6y agoWe don't know that the items are clearly numbers, arrays in Javascript are untyped. Your proposal is that Javascript's default sort algorithm should change behaviors based on whether it can do an extra O(n) loop over the entire array and check whether `typeof x === 'number'` evaluates to true for each index? I don't think that's a good idea.