Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting array after firstName and lastName, javascript

Currently I am sorting an array on firstName.

currentUsers = currentUsers.sort(function(a, b) {
    if (a.firstName > b.firstName) {
        return 1;
    } else if (a.firstName < b.firstName) {
        return -1;
    }
};

But I would like to have the lastName sorted as well. So that Bob Anderson would be sorted above Bob Bobson. I looked at another question here on stackoverflow which suggested that I should add:

currentUsers = currentUsers.sort(function(a, b) {
    if (a.firstName > b.firstName) {
        return 1;
    } else if (a.firstName < b.firstName) {
        return -1;
    }

    if (a.lastName > b.lastName) {
        return 1;
    } else if (a.lastName < b.lastName) {
        return -1;
    } else {
        return 0;
    }
};

//Edit The problem I have is that the sorting keeps sorting on every letter in firstName. How would I only sort on the first letter of firstName and then move on to the lastName?

like image 499
Reality-Torrent Avatar asked Sep 14 '25 15:09

Reality-Torrent


1 Answers

You can try this ES6 version

const currentUsers = [{
  firstName: "Bob",
  lastName: "Adler"
}, {
  firstName: "Barney",
  lastName: "Jones"
}, {
  firstName: "Freddie",
  lastName: "Crougar"
}, {
  firstName: "Bob",
  lastName: "Adams"
}, {
  firstName: "Joe",
  lastName: "Lewis"
}, {
  firstName: "Joseph",
  lastName: "Lewis"
}];

const sortedUsers = currentUsers.sort((a, b) => {
          const result = a.firstName.localeCompare(b.firstName);

          return result !== 0 ? result : a.lastName.localeCompare(b.lastName);
        })

console.log(sortedUsers);
like image 158
Amerzilla Avatar answered Sep 17 '25 04:09

Amerzilla