Reputation: 6110
I have a question about array.sort() method in JavaScript. Set of values in the array can vary from 1 to more. Sort function should sort them in the order if there is more than one element. Here is my code:
var myDates = ["03/05/2017","02/01/2017","03/02/2017"];
myDates.sort(function(a,b) {
a = a.split('/').reverse().join('');
b = b.split('/').reverse().join('');
return a > b ? 1 : a < b ? -1 : 0;
});
Code above works fine, all dates are sorted. My question is should I check the length of the array before I run the sort method? I'm asking this because my array can have one element only in some situations. So far my code did not throw any errors when I tested with one element only, but I would like to know if I should check the length of the array before I run the sort()
or JavaScript already takes care of that? If anyone knows the answer please let me know. Thank you.
Upvotes: 0
Views: 208
Reputation: 17398
This behaviour is documented in the Array.prototype.sort
specification. See http://www.ecma-international.org/ecma-262/6.0/#sec-array.prototype.sort
Specifically:
The arguments for calls to SortCompare are values returned by a previous call to the [[Get]] internal method, unless the properties accessed by those previous calls did not exist according to HasOwnProperty. If both perspective arguments to SortCompare correspond to non-existent properties, use +0 instead of calling SortCompare. If only the first perspective argument is non-existent use +1. If only the second perspective argument is non-existent use −1.
In short:
Array.prototype.sort((undefined, undefined) => { ... }); // => 0
Array.prototype.sort((undefined, b) => { ... }); // => 1
Array.prototype.sort((a, undefined) => { ... }); // => -1
Upvotes: 1