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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With