0

This question is different than ones pointed to because I want to sort by a string and THEN a number and a string, etc.

I have been going off of

javascript sort array by multiple (number) fields

I have the following for my data:

function GetStudentList(){
    var sl = [
    {
          "ClassOrder": 1,
          "LastName": "Blow",
          "FirstName": "Joe",
          "Class": "170-2"
    },
    {
          "ClassOrder": 2,
          "LastName": "Jane",
          "FirstName": "Sally",
          "Class": "170-1"
    },
    {
          "ClassOrder": 1,
          "LastName": "Belmont",
          "FirstName": "John",
          "Class": "170-1"
    }
]
return(sl);
}

Then I call the code:

var selectedStudents = GetStudentList();
selectedStudents.sort(function(a,b){
    return a.LastName - b,LastName;
};

It seems to work when I trace it in browser, but as soon as I leave the sort function, the selectedStudents array reverts back. It does appear to work, but only with the ClassOrder data. Then also, IF I try to sort by the ClassOrder and THEN the LastName, nothing works again.

return a.ClassOrder - b.ClassOrder || a.LastName - b.LastName
Community
  • 1
  • 1
Keltanis
  • 124
  • 1
  • 1
  • 9

1 Answers1

-1

You shouldn't compare strings with -. Instead, use < or > for sorting descending or ascending respectively.

let sl = [
  {
    "ClassOrder": 1,
    "LastName": "Blow",
    "FirstName": "Joe",
    "Class": "170-2"
  },
  {
    "ClassOrder": 2,
    "LastName": "Jane",
    "FirstName": "Sally",
    "Class": "170-1"
  },
  {
    "ClassOrder": 1,
    "LastName": "Belmont",
    "FirstName": "John",
    "Class": "170-1"
  }
];

sl.sort((a, b) => {
  if (a.LastName > b.LastName) return 1;
  else if (a.LastName < b.LastName) return -1;
  return 0;
});

console.log(sl);
Gavin
  • 4,365
  • 1
  • 18
  • 27