Is It Really A Array Sorting Bug Of Chrome And Ie?
Solution 1:
Since you have dates as string, its always better to create a date and check equality.
Comparing string can have issues as you can have date from any format. Classic example would be yyyy-m-d
.
In string comparison, 2017-1-12
is greater than 2017-08-17
.
var arr = ["2017-02-17", "2017-02-17", "2017-02-16", "2017-02-15", "2017-02-16", "2017-02-15", "2017-02-14", "2017-02-16", "2017-02-17", "2017-02-17", "2017-02-7", "2017-02-13"];
arr.sort(function(a, b) {
var d1 = newDate(a);
var d2 = newDate(b);
return +d1 - +d2;
})
console.log(arr)
Note: As pointed out by @K3N, if input will always be in ISO format, then you can use any way for string comparison (example @Nina Scholz's answer). But if there is a possibility of receiving input in any other format, I'd suggest comparing Date Objects instead.
Solution 2:
You might use the right comparison for Array#sort
and use it as return value, instead of a single true
/false
, which does eliminate the negative value, which is needed.
While you have ISO 6801 date strings, you could use String#localeCompare
for it.
var arr = ["2017-02-17", "2017-02-17", "2017-02-16", "2017-02-15", "2017-02-16", "2017-02-15", "2017-02-14", "2017-02-16", "2017-02-17", "2017-02-17", "2017-02-13"];
arr.sort(function(a, b) {
return a.localeCompare(b);
});
console.log(arr);
And if you do not care about Unicode code points, you could use Array#sort
The
sort()
method sorts the elements of an array in place and returns the array. The sort is not necessarily stable. The default sort order is according to string Unicode code points.
without compareFunction
var arr = ["2017-02-17", "2017-02-17", "2017-02-16", "2017-02-15", "2017-02-16", "2017-02-15", "2017-02-14", "2017-02-16", "2017-02-17", "2017-02-17", "2017-02-13"];
arr.sort();
console.log(arr);
Solution 3:
You have to use simply sort without passing a callback
function.
arr.sort();
var arr = ["2017-02-17",
"2017-02-17",
"2017-02-16",
"2017-02-15",
"2017-02-16",
"2017-02-15",
"2017-02-14",
"2017-02-16",
"2017-02-17",
"2017-02-17",
"2017-02-13"];
arr.sort();
console.log(arr);
Post a Comment for "Is It Really A Array Sorting Bug Of Chrome And Ie?"