Write sorting for date and name in JavaScript?

1.1k Views Asked by At

How to write sorting for date and name in ? 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"]
3

There are 3 best solutions below

5
On BEST ANSWER

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);

0
On

To sort strings :

array.sort(function(a, b) {
    var titleA = a.title.toLowerCase(), titleB = b.title.toLowerCase();
    if (titleA < titleB) return -1;
    if (titleA > titleB) return 1;
    return 0;
});

To sort dates :

array.sort(function(a, b) {
    var dateA = new Date(a.release), dateB = new Date(b.release);
    return dateA - dateB;
});

Refer to this document https://en.proft.me/2015/11/14/sorting-array-objects-number-string-date-javascrip/ for more details.

0
On

to do it properly I'd combine the answers of sudip and wentjun

strings:

name.sort((a, b) => a.localeCompare(b, 'en', { numeric: true }));

dates:

createdDate.sort((a, b) => Date.parse(a) - Date.parse(b));