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
CodePudding user response:
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);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
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