Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gordey4doronin/51e3940d714c17b3bb6099ae9d0dd330 to your computer and use it in GitHub Desktop.
Save gordey4doronin/51e3940d714c17b3bb6099ae9d0dd330 to your computer and use it in GitHub Desktop.
This code snippet aims to demonstrate the difference between Node 10 and Node 12 Array.sort implementations.
// This code snippet aims to demonstrate the difference between Node 10 and Node 12 Array.sort implementations.
// The result is guaranteed to be sorted.
// However, the order is not guaranteed.
// For better understanding see v8 array-sort blog post https://v8.dev/blog/array-sort.
// Related discussion in node repo https://github.com/nodejs/node/issues/24294.
// Below we have multiple members with the same `num` values.
// The `title` properties are here for visibility, they're not used for sorting.
// In Node 12 we receive known pangrams in the sorted result.
// "The quick brown fox jumps over the lazy dog"
// "The five boxing wizards jump quickly"
// While in Node 10 the order is slightly different for the elements with equal `id` values.
var arr = [
{ num: 10, title: 'quickly' },
{ num: 9, title: 'wizards' },
{ num: 9, title: 'jump' },
{ num: 8, title: 'dog' },
{ num: 8, title: 'The' },
{ num: 8, title: 'five' },
{ num: 8, title: 'boxing' },
{ num: 7, title: 'lazy' },
{ num: 6, title: 'the' },
{ num: 5, title: 'over' },
{ num: 4, title: 'jumps' },
{ num: 3, title: 'fox' },
{ num: 2, title: 'brown' },
{ num: 1, title: 'The' },
{ num: 1, title: 'quick' }
]
// Now using node v12.21.0
arr.sort((a, b) => a.num - b.num)
// [
// { num: 1, title: 'The' },
// { num: 1, title: 'quick' },
// { num: 2, title: 'brown' },
// { num: 3, title: 'fox' },
// { num: 4, title: 'jumps' },
// { num: 5, title: 'over' },
// { num: 6, title: 'the' },
// { num: 7, title: 'lazy' },
// { num: 8, title: 'dog' },
// { num: 8, title: 'The' },
// { num: 8, title: 'five' },
// { num: 8, title: 'boxing' },
// { num: 9, title: 'wizards' },
// { num: 9, title: 'jump' },
// { num: 10, title: 'quickly' }
// ]
// Now using node v10.24.0
arr.sort((a, b) => a.num - b.num)
// [ { num: 1, title: 'quick' },
// { num: 1, title: 'The' },
// { num: 2, title: 'brown' },
// { num: 3, title: 'fox' },
// { num: 4, title: 'jumps' },
// { num: 5, title: 'over' },
// { num: 6, title: 'the' },
// { num: 7, title: 'lazy' },
// { num: 8, title: 'boxing' },
// { num: 8, title: 'five' },
// { num: 8, title: 'The' },
// { num: 8, title: 'dog' },
// { num: 9, title: 'wizards' },
// { num: 9, title: 'jump' },
// { num: 10, title: 'quickly' } ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment