How to write sorting for date and name in javascript? I have one table. There are 2 columns: name
and created date
:
name: ["A", "A9", "A10", "A11", "A3"]
createdDate: ["Apr 2, 2019 3:07 PM", "Apr 10, 2019 9:25 AM", "Apr 30, 2019 6:08 PM", "Apr 10, 2019 8:25 AM", "Apr 2, 2019 8:07 PM"]
I already try using sort method. Output should like this:
name: ["A", "A3", "A9", "A10", "A11"]
createdDate: ["Apr 2, 2019 3:07 PM", "Apr 2, 2019 8:07 PM","Apr 10, 2019 8:25 AM", "Apr 10, 2019 9:25 AM", "Apr 30, 2019 6:08 PM"]
This is how you can sort the name
array alphanumerically, using localeCompare(), and passing numeric as one of the options.
const name = ["A", "A9", "A10", "A11", "A3"];
name.sort((a, b) => a.localeCompare(b, 'en', { numeric: true }));
console.log(name);
Here is how you can sort them by dates. Essentially, we convert them to JavaScript date objects when doing the comparison.
const createdDate = ["Apr 2, 2019 3:07 PM", "Apr 2, 2019 8:07 PM","Apr 10, 2019 8:25 AM", "Apr 10, 2019 9:25 AM", "Apr 30, 2019 6:08 PM"];
createdDate.sort((a, b) => new Date(a) - new Date(b));
console.log(createdDate);