2

I would like to know how can I sort dates in javascript containing comma-separated values in different order e.g.

var dates = "6/11/2015, 6/1/2015, 6/22/2015, 6/7/2015, 5/11/2015";

I want to order dates by latest dates like,

var dates2 = "5/11/2015, 6/1/2015, 6/7/2015, 6/11/2015, 6/22/2015";

Your help will be appreciated. Thanks

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
greentea
  • 23
  • 2
  • How about putting the dates in an array and then using the sorting method? – Matthew Oct 26 '21 at 21:26
  • 1
    Check out [split](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split), [sort](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort), and [join](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join). – ray Oct 26 '21 at 21:26
  • getTime() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTime – Matthew Oct 26 '21 at 21:40

2 Answers2

5

You can split the string to get an array, sort them by passing each string to the Date constructor, and then join it back together.

let dates = "6/11/2015, 6/1/2015, 6/22/2015, 6/7/2015, 5/11/2015";
let res = dates.split(", ").sort((a,b)=>new Date(a) - new Date(b)).join(", ");
console.log(res);
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
  • My instinct would be to convert to date objects and sort those, leaving the need to format back to strings. This is cool, but probably better practical advice is to keep objects around instead of strings, formatting only when a human needs to read them. – danh Oct 26 '21 at 21:34
  • See [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) – RobG Oct 27 '21 at 00:55
  • @greentea Glad to help. – Unmitigated Oct 27 '21 at 16:46
1

The way I think, this could be done easily using split() to extract each day, month, year, and then, use those values to construct Dates objects. Finally, you compare and sort those dates.

const splitDatesByComma = dates.split(',').map((el) => el.trim())
            
const dates = splitDatesByComma.map((el) => {
  const splitDate = el.split('/')
                
  // Create a Date for splitted string. Month is 0 based
  return new Date(splitDate[2], splitDate[1] - 1, splitDate[0], 0, 0, 0, 0)
})
            
const sortDatesDescending = dates.sort((dateA, dateB) => {
  if (dateA > dateB) {
    return -1
  }
  if (dateA < dateB) {
    return 1
  }
    return 0
  })

// Format sorted dates to string and join them.
const datesFormattedAndSorted = sortDatesDescending.map((date) => {
  return `${date.getDate()}/${date.getMonth() + 1}/${date.getFullYear()}`
})
console.log(datesFormattedAndSorted.join(', '))

I've done this at CodePen with Vue if anyone is interested: https://codepen.io/LucasFer/pen/mdMmqrN

Lucas David Ferrero
  • 1,630
  • 14
  • 40
  • The parse can be much simpler: `let [m, d, y] = date.split(/\D/); new Date(y, m-1, d);`. :-) You could also use a regular expression for splitting the dates string like `/,\s*/`. – RobG Oct 27 '21 at 01:14