Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort date array in javascript

I have below array of dates and I want to sort it in acceding order. I tried but not getting the positive result.

var arr = [ [ '02/13/2015', 0.096 ],
  [ '11/15/2013', 0.189 ],
  [ '05/15/2014', 0.11 ],
  [ '12/13/2013', 0.1285 ],
  [ '01/15/2013', 0.12 ],
  [ '01/15/2014', 0.11 ],
  [ '02/14/2014', 0.11 ],
  [ '03/14/2014', 0.11 ],
  [ '01/15/2015', 0.096 ],
  [ '07/15/2015', 0.096 ],
  [ '04/15/2013', 0.12 ],
  [ '04/15/2014', 0.11 ],
  [ '05/15/2013', 0.12 ],
  [ '06/14/2013', 0.12 ],
  [ '06/16/2014', 0.11 ],
  [ '07/15/2013', 0.12 ],
  [ '07/15/2014', 0.11 ],
  [ '03/16/2015', 0.096 ]]

My Code

arr.sort(function(a,b){
  return new Date(a[0][0]) - new Date(b[0][0]);
});
like image 235
Rakesh Kumar Avatar asked Jan 29 '26 22:01

Rakesh Kumar


1 Answers

You are taking the first character in the date strings, converting them to Date instances and using them for comparison.

But, you should actually use the Date strings as they are, convert them to Date instances and compare them.

arr.sort(function (a, b) {
  return new Date(a[0]) - new Date(b[0]);
});

Output

[ [ '01/15/2013', 0.12 ],
  [ '04/15/2013', 0.12 ],
  [ '05/15/2013', 0.12 ],
  [ '06/14/2013', 0.12 ],
  [ '07/15/2013', 0.12 ],
  [ '11/15/2013', 0.189 ],
  [ '12/13/2013', 0.1285 ],
  [ '01/15/2014', 0.11 ],
  [ '02/14/2014', 0.11 ],
  [ '03/14/2014', 0.11 ],
  [ '04/15/2014', 0.11 ],
  [ '05/15/2014', 0.11 ],
  [ '06/16/2014', 0.11 ],
  [ '07/15/2014', 0.11 ],
  [ '01/15/2015', 0.096 ],
  [ '02/13/2015', 0.096 ],
  [ '03/16/2015', 0.096 ],
  [ '07/15/2015', 0.096 ] ]
like image 71
thefourtheye Avatar answered Jan 31 '26 23:01

thefourtheye