user3631204
user3631204

Reputation: 21

Is it really a array sorting bug of chrome and ie?

I create a very simple array sorting script, it works on Firefox, but chrome and ie are giving me an unordered array.

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>b;});
console.log(arr);

Is is a chrome/ie bug or I missed something? I hardly believe that chrome and ie have differenrt js engine have the same issue.

Upvotes: 0

Views: 598

Answers (3)

Nina Scholz
Nina Scholz

Reputation: 386700

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);

Upvotes: 2

Rajesh
Rajesh

Reputation: 24945

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 = new Date(a);
  var d2 = new Date(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.

Upvotes: 2

Mihai Alexandru-Ionut
Mihai Alexandru-Ionut

Reputation: 48407

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);

Upvotes: 1

Related Questions