I was reading my daily set of random reference pages and found out that poor undefined always goes last regardless of your comparison function. An interesting find.
const arr = ['saab', 'toyota', undefined, 'volvo']
arr.sort((a, b) => {
console.log('cmp', a, 'vs', b)
if (String(a) < String(b)) return -1
if (String(a) > String(b)) return 1
return 0
})
console.log(arr)
cmp toyota vs saab
cmp volvo vs toyota
[ 'saab', 'toyota', 'volvo', undefined ]
If compareFn is supplied, all non-undefined array elements are sorted according to the return value of the compare function (all undefined elements are sorted to the end of the array, with no call to compareFn).
1 comment
[ 2.5 ms ] story [ 14.8 ms ] threadI was reading my daily set of random reference pages and found out that poor undefined always goes last regardless of your comparison function. An interesting find.
If compareFn is supplied, all non-undefined array elements are sorted according to the return value of the compare function (all undefined elements are sorted to the end of the array, with no call to compareFn).