.sort strange behavior

classic Classic list List threaded Threaded
4 messages Options
Reply | Threaded
Open this post in threaded view
|

.sort strange behavior

Cyril Auburtin
```js
[0,1,3,4,7,8,8,9,13,17,22,23,26].concat([16,19,21,22,25,32]).sort((a,b)=>a-b)
// [ 0, 1, 3, 4, 7, 8, 8, 9, 13, 16, 17, 19, 21, 22, 22, 23, 25, 26, 32 ]

[0,1,3,4,7,8,8,9,13,17,22,23,26].concat([16,19,21,22,25,32]).sort()
// [ 0, 1, 13, 16, 17, 19, 21, 22, 22, 23, 25, 26, 3, 32, 4, 7, 8, 8, 9 ]
```
In the second case, it produces a weirdly sorted array, on node 8, chrome or firefox

What could explain this?

_______________________________________________
es-discuss mailing list
[hidden email]
https://mail.mozilla.org/listinfo/es-discuss
Reply | Threaded
Open this post in threaded view
|

Re: .sort strange behavior

Damian Senn-2

_______________________________________________
es-discuss mailing list
[hidden email]
https://mail.mozilla.org/listinfo/es-discuss
Reply | Threaded
Open this post in threaded view
|

Re: .sort strange behavior

Cyril Auburtin
Oh thanks right, alphabetical order by default so

2017-10-21 15:00 GMT+02:00 Damian Senn <[hidden email]>:


_______________________________________________
es-discuss mailing list
[hidden email]
https://mail.mozilla.org/listinfo/es-discuss
Reply | Threaded
Open this post in threaded view
|

Re: .sort strange behavior

Mark Volkmann
In reply to this post by Cyril Auburtin
By default sort converts the values to strings and compares there Unicode values. For example, 10 would come before 3. In the first example you are overriding the default sort comparison in a way that is correct for numbers.

---
R. Mark Volkmann
Object Computing, Inc.

> On Oct 21, 2017, at 7:57 AM, Cyril Auburtin <[hidden email]> wrote:
>
> ```js
> [0,1,3,4,7,8,8,9,13,17,22,23,26].concat([16,19,21,22,25,32]).sort((a,b)=>a-b)
> // [ 0, 1, 3, 4, 7, 8, 8, 9, 13, 16, 17, 19, 21, 22, 22, 23, 25, 26, 32 ]
>
> [0,1,3,4,7,8,8,9,13,17,22,23,26].concat([16,19,21,22,25,32]).sort()
> // [ 0, 1, 13, 16, 17, 19, 21, 22, 22, 23, 25, 26, 3, 32, 4, 7, 8, 8, 9 ]
> ```
> In the second case, it produces a weirdly sorted array, on node 8, chrome or firefox
>
> What could explain this?
> _______________________________________________
> es-discuss mailing list
> [hidden email]
> https://mail.mozilla.org/listinfo/es-discuss
_______________________________________________
es-discuss mailing list
[hidden email]
https://mail.mozilla.org/listinfo/es-discuss