5 ms·
> [1,10,5,-15,-2,4].sort(function(a,b) {return a > b}) [ -15, -2, 1, 4, 5, 10 ] > [1,10,5,-15,-2,4].sort(function(a,b
by robinduckett 13y ago
> [1,10,5,-15,-2,4].sort(function(a,b) {return a > b})
[ -15,
-2,
1,
4,
5,
10 ]
> [1,10,5,-15,-2,4].sort(function(a,b) {return ""+a > ""+b})
[ -15,
-2,
1,
10,
4,
5 ]
Perhaps .sort was initially designed to do something else, like sorting strings, rather than integers.
- adamnemecek 13y agoI'm pretty sure that the parent comment's author is aware of this. It does not change the fact that it's broken.
- tjansen 13y agoWhy? Sorting strings is a far more common thing to do than just sorting numbers, so it makes sense to use simple string comparisons as the default algorithm. Rather than come up with something that first evaluates the types in the list and then tries to figure out what to do.
- dsl 13y agoNo, it makes sense to sort strings when you get handed strings, and sort numbers when handed numbers. Period. Default behavior is now exactly as expected by 100% of developers. Your creativity as a language designer should only come in to play when dealing with sets of mixed type.
- Yaggo 13y agoSo how should [1, "a", 2, 3] be sorted by default?
- integraton 13y agoBoth Python and Erlang would return [1,2,3,"a"], Ruby and Clojure won't allow the comparison. Either of these approaches makes more sense than JavaScript's.
- bpicolo 13y agoJavascript returns [1,2,3,a]. What's the problem.
- integraton 13y ago> [1,2,"10",3].sort() [ 1, '10', 2, 3 ] That's the problem.
- esailija 13y agoI don't know - it's just a default general API, obviously it's not going to match everyone's use case. I would say that even relying on sort made by someone else is already not fit for many use cases. If such a petty and trivial "problem" is what you have against Javascript, then you are basically saying it's a good language :--)
- integraton 13y agoYet somehow it works just fine out of the box in plenty of other languages, including Python, Erlang, Clojure, Ruby, etc.
- adamnemecek 13y agoYeah, plus it's not just thing one thing, but there is a good amount of seemingly little things like this that add up.
- masklinn 13y agoOr you're saying that you know so little about it you don't know of its real problems.
- Kiro 13y agoIt's not broken.
- robinduckett 13y agoNot when I posted this, he's edited his comment.