Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Safari doesn't sort array of objects like others browsers [duplicate]

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?

like image 811
Simon Arnold Avatar asked Mar 19 '13 18:03

Simon Arnold


People also ask

How do you sort an array of objects?

To sort an array of objects in JavaScript, use the sort() method with a compare function. A compare function helps us to write our logic in the sorting of the array of objects. They allow us to sort arrays of objects by strings, integers, dates, or any other custom property.

Does sort mutate array JavaScript?

The sort() method returns a reference to the original array, so mutating the returned array will mutate the original array as well.

How do you sort an array in ascending order?

Example: Sort an Array in Java in Ascending Order Then, you should use the Arrays. sort() method to sort it. That's how you can sort an array in Java in ascending order using the Arrays. sort() method.

How to sort an array of strings JavaScript?

In JavaScript arrays have a sort( ) method that sorts the array items into an alphabetical order. The sort( ) method accepts an optional argument which is a function that compares two elements of the array. If the compare function is omitted, then the sort( ) method will sort the element based on the elements values.


2 Answers

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;
});
like image 64
Blazemonger Avatar answered Oct 23 '22 17:10

Blazemonger


"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);
});
like image 1
Rocket Hazmat Avatar answered Oct 23 '22 18:10

Rocket Hazmat