Home > Software engineering >  How to sort the string of date format in an array
How to sort the string of date format in an array

Time:03-22

Input

var data = ["09 may 2015", "25 december 2015", "22 march 2015", "25 june 2016", "18 august 2015"];

output 22 March 2015, 09 May 2015, 18 August 2015, 25 December 2015, 25 jun 2016

CodePudding user response:

Subtracting 2 dates returns the difference between the two dates in milliseconds if a date is smaller than b returns negative values a will sorted to be a lower index than b.

var data = ["09 may 2015", "25 december 2015", "22 march 2015", "25 june 2016", "18 august 2015"];


data.sort(function(a,b){
  return  new Date(a) - new Date(b);
});
console.log(data);

CodePudding user response:

As noted in comments, one simple solution would be to use new Date(). Since OP requested for a possible method without new Date(), the below solution may be able to achieve the desired objective.

Code Snippet

// set-up a map/object to map "january": "01", "february": "02", etc
const monthMap = Object.fromEntries(
  "january,february,march,april,may,june,july,august,september,october,november,december"
  .split(',').map(
    (month, idx) => ([month, idx.toString().padStart(2, '0')])
  )
);

// use the map/object to convert month into 2-char string
const monthToNum = m => m.toLowerCase() in monthMap ? monthMap[m.toLowerCase()] : '99';

// reformat date from dd MMM yyyy to yyyy-mm-dd
const reformatDate = dt => {
  const parts = dt.split(' ');
  return [parts[2], monthToNum(parts[1]), parts[0]].join('-');
};

// use the custom-made "reformat" method to sort
const sortData = arr => arr.sort((a, b) => reformatDate(a) > reformatDate(b) ? 1 : -1);

// actual data from OP's question
const data = ["09 may 2015", "25 december 2015", "22 march 2015", "25 june 2016", "18 august 2015"];

// invoke the sort-method and console.log the result
console.log(sortData(data));

Explanation

Comments have been added in-line within the code-snippet above. If any further questions, please use comments below.

  • Related