QWERTY
QWERTY

Reputation: 2315

Sorting date in string format using JavaScript

I got this list of date array that I am trying to sort:

var arr = ['2017/12/16', 
'2017/05/01',
'2017/04/20',
'2017/03/10',
'2017/08/12',
'2017/03/06',
'2017/02/04',
'2017/01/07',
'2016/02/08',
'2015'09/08'];

They are in yyyy/mm/dd format. I tried to use this function to sort:

arr.sort(function(a,b) {
 a = a.split('/').reverse().join('');
  b = b.split('/').reverse().join('');
  return a > b ? 1 : a < b ? -1 : 0;
});

However, it tells me that a.split is not a function.

Upvotes: 0

Views: 1453

Answers (2)

Patrick Hund
Patrick Hund

Reputation: 20246

There is no need to convert the strings in your array, you can simply compare strings by using the default behavior of Array#sort:

var arr = [
    '2017/12/16',
    '2017/05/01',
    '2017/04/20',
    '2017/03/10',
    '2017/08/12',
    '2017/03/06',
    '2017/02/04',
    '2017/01/07',
    '2016/02/08',
    '2015/09/08'
];

arr.sort();

console.log(arr);

Upvotes: 3

Dekel
Dekel

Reputation: 62626

Instead of split/reverse/join just convert the string to Date object and let javascript do the sorting for you:

var arr = ['2017/12/16', 
'2017/05/01',
'2017/04/20',
'2017/03/10',
'2017/08/12',
'2017/03/06',
'2017/02/04',
'2017/01/07',
'2016/02/08',
'2015/09/08'
];

arr.sort(function(a, b) {
  da = new Date(a);
  db = new Date(b);
  if (da == db) {
    return 0;
  }
  return da > db ? 1 : -1;
});

console.log(arr);

Upvotes: 1

Related Questions