3 ms·
That would have undesirable side effects - e.g. it would mean the results of the sort are not necessarily specified. If the array contains NaN, for example, cal
by fenomas 11y ago
That would have undesirable side effects - e.g. it would mean the results of the sort are not necessarily specified. If the array contains NaN, for example, calling a sort like that would have different results depending on the order in which the elements are compared, which would likely vary by JS engine.
- CJefferson 11y agoI don't really understand your problem -- this is how array comparison is implemented in C++, Python, Ruby, Java (when using the default isComparable on most array-list types) and Haskell (from the languages I use frequently). Javascript is the only weird outlier.
- fenomas 11y agoI don't know what you're taking issue with. The results of sorting in JS with a simple (a<b) comparison will necessarily vary by JS implementation, and I'm suggesting that would be a drawback for a default specified behavior. E.g.: [1,3,NaN,2,5].sort( (a,b) => a<b ? -1 : 1 ) // Chrome: [ NaN, 1, 2, 3, 5 ] // Firefox: [ 2, 5, NaN, 1, 3 ]
- CJefferson 11y agoI am refering to this: In (almost) every other language ever the following is true. In Javascript it is false. [2] < [11] This means: [[2], [11]].sort() // Javascript: [ [11], [2] ]
- fenomas 11y agoYou're overlapping a couple of separate things. The article and my initial comment were about sorting arrays of numbers. If you're sorting arrays of arrays, the behavior of ([2] < [11]) is slightly beside the point, since Array.sort() doesn't compare the arrays, it converts all elements to strings first. As for the actual behavior of ([2] < [11]), the issue there is that "Array" is not a type in JS, arrays are just objects that happen to have properties called "0" and "1" and so on. Hence operators don't have any special cases for arrays, so getting comparisons to work like you had hoped would mean the comparison operator would need weird special rules where, whenever it's passed two objects it checks if they both have properties called "0", and if so do one thing, if not do something else, etc.