Think about the below trivial problem: Sort the activities by date in ascending order:
const activities = [
{ title: 'Hiking', date: new Date('2019-06-28') },
{ title: 'Shopping', date: new Date('2019-06-10') },
{ title: 'Trekking', date: new Date('2019-06-22') }
]
Sounds trivial right?
var output = activities.sort( (a, b) => a.date > b.date);
Emm, you tried this in Node.js, in npm runkit, all looks right. The sorted result is
Shopping --> Trekking --> Hiking
However, if you run this code in the Chrome browser, you will see a different result! The result is still the same as the input, which is
Hiking --> Shopping --> Trekking
Why is that?
The reason is, the sort function accepts a comparator (the lambda or arrow function above) to be an integer, not a boolean!
Below is the documentation fromMozilla:
If compareFunction
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 compareFunction
). If a
and b
are two elements being compared, then:
- If
compareFunction(a, b)
returns less than 0, sorta
to an index lower thanb
(i.e.a
comes first). - If
compareFunction(a, b)
returns 0, leavea
andb
unchanged with respect to each other, but sorted with respect to all different elements. Note: the ECMAscript standard does not guarantee this behavior, thus, not all browsers (e.g. Mozilla versions dating back to at least 2003) respect this. - If
compareFunction(a, b)
returns greater than 0, sortb
to an index lower thana
(i.e.b
comes first). compareFunction(a, b)
must always return the same value when given a specific pair of elementsa
andb
as its two arguments. If inconsistent results are returned, then the sort order is undefined.
Soif you run below code:Note the difference of
const output = activities.sort( (a, b) => a.date - b.date);
//(a, b) => a.date > b.date ➜ (a, b) => a.date - b.date
That is it!
So to recap, the Javascript in the browser may be different from the one ran on node.js. Read the official documents to make sure we are using the correct one.