Safari doesn't sort array of objects like othe

2019-02-08 18:47发布

问题:

This question already has an answer here:

  • Why won't Safari 5 sort an array of objects? 1 answer
var myArray = [{date:"2013.03.01"},{date:"2013.03.08"},{date:"2013.03.19"}];

I tried:

function(a,b){
  return b.date > a.date;
}

and

function(a,b){
  return b.date - a.date;
}

The console.log in Chrome and Firefox give me the desired output:

"2013.03.19", "2013.03.08", "2013.03.01"

but Safari give the original sorting:

"2013.03.01", "2013.03.08", "2013.03.19"

Why?

回答1:

A sort function in JavaScript is supposed to return a real number -- not true or false or a string or date. Whether that number is positive, negative, or zero affects the sort result.

Try this sort function (which will also correctly sort any strings in reverse-alphabetical order):

myArray.sort(function(a,b){
  return (b.date > a.date) ? 1 : (b.date < a.date) ? -1 : 0;
});


回答2:

"2013.03.01" is not a date. It's a string.

In order to correctly sort by dates, you need to convert these to dates (timestamps).

var myArray = [{date:"2013.03.01"},{date:"2013.03.08"},{date:"2013.03.19"}];

myArray.sort(function(a,b){
    return Date.parse(b.date) - Date.parse(a.date);
});

You might also be able to sort them using direct string comparasions too:

myArray.sort(function(a,b){
    return b.date.localeCompare(a.date);
});