Markus
Markus

Reputation: 33

Javascript sort not working in Firefox

I have the following code which is sorting a list of javascript objects in an array based on their date. The data is coming from an XML file. The date is formatted as follows: MM-DD-YYYY

concert=new Object();
concert.performer=performerName;
concert.date=concertDate;
concerts[0]=concert; //adding to array in a for loop

So at this stage I have a load of concert objects in my concerts array. I then go to sort it and output it to a table:

sortedConcerts = concerts.sort(sortConcerts);

function sortConcerts(a, b){
var firstConcert=new Date(a.date);
var secondConcert=new Date(b.date);
return firstConcert-secondConcert;
}

I then have the new sorted array which I print out using a table or whatever.

My problem is that this works fine in IE and Chrome, but not in Firefox... what does Firefox not like?

Upvotes: 3

Views: 3163

Answers (4)

Дима
Дима

Reputation: 1

Try to use sortBy from loadesh

const result = sortBy(array, item => item.your.deep.data)          
return (currentDirection === 'asc') ? result : result.reverse()

Upvotes: 0

Sandeep G B
Sandeep G B

Reputation: 4015

Here is functioning code fiddle

I verified on IE, Chrome & FF.

Upvotes: 0

Dennis
Dennis

Reputation: 32608

Firefox seems to accept:

new Date("Jan 1 2009");
new Date("January 1 2009");
new Date("1 1 2009");
new Date("1/1/2009");

However using the hyphens gives you an invalid date format, which results in NaN for mathematic operations, (in your case, subtraction);

new Date("1/1/2009") - new Date("1-1-2009"); // NaN in Firefox, 0 in other browsers
new Date("1/1/2009") - new Date("1/1/2009"); // 0 in all browsers.

MDN has an article on valid date formats.

Upvotes: 2

Pointy
Pointy

Reputation: 413866

Your date format ("MM-DD-YYYY") is not valid. Thus your "Date" instances are always identical.

You could flip the strings around and just compare as strings:

function sortConcerts(a, b) {
  function flipDate(d) {
    return d.replace(/(\d\d)-(\d\d)-(\d\d\d\d)/, "$3-$1-$2");
  }

  var d1 = flipDate(a.date), d2 = flipDate(b.date);
  return d1 > d2 ? 1 : d2 > d1 ? -1 : 0;
}

Firefox insists on dates following IETF standards (I think it's from RFC-822 originally).

If there are a zillion concerts, it'd be more efficient to flip the dates around for all the concerts before sorting them.

Upvotes: 2

Related Questions