Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Sort Function with more than one criteria

Here is a sample of what I am sorting:

[
  ['Zed Jones', '24 Nov 2017 2:00 PM'],
  ['Jack Mo', '25 Nov 2017 5:00 PM'],
  ['John Phil', '25 Nov 2017 4:00 PM'],
  ['Bob Phil', '25 Nov 2017 4:00 PM']
]

Here is my desired output:

[
  ['Zed Jones', '24 Nov 2017 2:00 PM'],
  ['Bob Phil', '25 Nov 2017 4:00 PM'],
  ['John Phil', '25 Nov 2017 4:00 PM'],
  ['Jack Mo', '25 Nov 2017 5:00 PM']
]

Notice how the output is sorted by day, hour, and first letter of first name

Here is my code below. I have been able to sort by day and hour pretty easily but I am having trouble finding a way to compare and place first letter of first name:

function sortTable(data) {
  return data.sort((elem1, elem2) => {
    var dateA      = new Date(elem1[1])
      , dateB      = new Date(elem2[1])

    return dateA.getHours() - dateB.getHours() + dateB.setHours(0) - dateA.setHours(0);
  });
}

I have tried to sort once by date and then perform another sort function comparing the first letter of each first name, but I am having issues as it does not properly sort the data:

function sortTable(data) {
  // Sort by date and time
  data = data.sort((elem1, elem2) => {
    var dateA      = new Date(elem1[1])
      , dateB      = new Date(elem2[1])

    return dateA.getHours() - dateB.getHours() + dateB.setHours(0) - dateA.setHours(0);
  });

  // Then sort by name and return data
  return data.sort((elem1, elem2) => {
    var name1 = elem1[0]
      , name2 = elem2[0]
      , let1
      , let2;

    // Check that we have a name available
    if (name1 !== undefined) let1 = name1.charAt(0);
    if (name2 !== undefined) let2 = name2.charAt(0);

      return let1 < let2;
  });
 }

In what ways can I modify this code to achieve my desired output? Any help would be greatly appreciated. Thank you in advance!

like image 282
szier Avatar asked Mar 14 '26 04:03

szier


1 Answers

You could take the delta of the second element as date difference and take the first character for sorting if the delta is zero of the date

var data = [['Zed Jones', '24 Nov 2017 2:00 PM'], ['Jack Mo', '25 Nov 2017 5:00 PM'], ['John Phil', '25 Nov 2017 4:00 PM'], ['Bob Phil', '25 Nov 2017 4:00 PM']];

data.sort(function (a, b) {
    return new Date(a[1]) - new Date(b[1]) || a[0][0] > b[0][0] || -(a[0][0] < b[0][0]);
});

console.log(data);
like image 168
Nina Scholz Avatar answered Mar 15 '26 16:03

Nina Scholz