0

In this line of code which concats two arrays and multiplies each value by 2:

[[3,2,1],[6,5,4]].reduce(function(p,c,i,a) {
    return p.concat(c) 
}).map(function(v) {
    return v * 2 
}).sort()

I would expect the final output to be sorted, but it is not. The result is:

[10, 12, 2, 4, 6, 8]

If I put the sort in earlier, it comes back sorted:

[[3,2,1],[6,5,4]].reduce(function(p,c,i,a) {
    return p.concat(c) 
}).sort().map(function(v) {
    return v * 2 
})

Result:

[2, 4, 6, 8, 10, 12]

What is going on here? This is not a duplicate question, as noted below. And the duplicate cited is incorrect as well. .sort will indeed sort numbers:

[10,12,2,4,6,8].sort() = [2,4,6,8,10,12]
eeejay
  • 5,394
  • 8
  • 29
  • 30
  • See also http://stackoverflow.com/questions/1063007/arr-sort-does-not-sort-integers-correctly – p.s.w.g Oct 28 '14 at 15:15
  • This is not a duplicate question, the referenced duplicate is a different question, and the answer is also incorrect. Javascript sort prototype will indeed sort numbers. – eeejay Oct 28 '14 at 15:52
  • 1
    What browser are you using where `[10,12,2,4,6,8].sort()` gives you `[2,4,6,8,10,12]`? It gives me `[10,12,2,4,6,8]` in Firefox 34.0. Not entirely convinced it's a duplicate question, though, since that other one doesn't address why calling `sort()` and `map()` in different orders affects the results. – Anthony Grist Oct 28 '14 at 16:17
  • The problem is essentially the same. If you sort first, the array you're sorting is `[3, 2, 1, 6, 5, 4]`, but if you sort last, the array you're sorting is `[6, 4, 2, 12, 10, 8]`, and because `sort` uses alphabetical sorting by default, you'll get different results. (i.e. `2` < `12` but `"12"` < `"2"`) – p.s.w.g Oct 28 '14 at 18:52

0 Answers0