I have the following array in JavaScript, I need to sort them by last name.
var names = [Jenny Craig, John H Newman, Kelly Young, Bob];
Results would be:
Bob,
Jenny Craig,
John H Newman,
Kelly Young
Any examples on how to do this?
Try this:
const names = ["John H Newman", "BJenny Craig", "BJenny Craig", "Bob", "AJenny Craig"];
const compareStrings = (a, b) => {
if (a < b) return -1;
if (a > b) return 1;
return 0;
}
const compare = (a, b) => {
const splitA = a.split(" ");
const splitB = b.split(" ");
const lastA = splitA[splitA.length - 1];
const lastB = splitB[splitB.length - 1];
return lastA === lastB ?
compareStrings(splitA[0], splitB[0]) :
compareStrings(lastA, lastB);
}
console.log(names.sort(compare));
function lastNameSort(a,b) {
return a.split(" ").pop()[0] > b.split(" ").pop()[0]
};
names.sort(lastNameSort);
This was inspired by this answer.
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