Javascript: sort arrays containing dates in descending order

I have the following array:

var times = [ ["04/11/10", "86kg"], ["05/12/11", "90kg"], ["06/12/11", "89kg"] ]; 

I want to list these dates and their respective weights in ascending order.

I know that you can sort arrays with sorting, and I found the following function from this About.com page , which I thought would do what I wanted:

 times.sort(dmyOrdA); var dateRE = /^(\d{2})[\/\-](\d{2})[\/\-](\d{2})/; function dmyOrdA(a,b) { a = a.replace(dateRE, "$3$2$1"); b = b.replace(dateRE, "$3$2$1"); if (a > b) { return 1; } else if (a < b) { return -1; } else { return 0; } } 

However, using this function, I get the following error:

 a.replace is not a function 

Can anyone help with my request?

Thanks in advance.

EDIT:

Looking at the previous stack overflow question, it looks like in my case, โ€œaโ€ is not a string. However, I do not understand why this is so.

+4
source share
2 answers

when sorting an array, the parameters that the sort function performs are elements of the array.
In your case, the elements of the array are also arrays ... bummer.
You want to sort an array of arrays by the first element of each element (harder).
Therefore, simply change the values โ€‹โ€‹of a and b to a[0] and b[0] :

 function dmyOrdA(a,b) { a = a[0].replace(dateRE, "$3$2$1"); b = b[0].replace(dateRE, "$3$2$1"); if (a > b) return 1; else if (a < b) return -1; else return 0; } 

You got a.replace is not a function because replace is a String method and you tried to apply it to Array

+3
source

You must convert to the appropriate dates and then subtract in the comparison functions:

 function dmyOrdA(a,b){return myDate(a[0]) - myDate(b[0]);} function myDate(s){var a=s.split("/"); return new Date("20"+a[2],a[1]-1,a[0]);} 
0
source

All Articles