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?
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?
Share Improve this question edited Jun 11, 2014 at 22:00 mucio 7,1191 gold badge22 silver badges36 bronze badges asked Jun 11, 2014 at 21:55 Jeffrey MessickJeffrey Messick 991 gold badge1 silver badge5 bronze badges 4 |3 Answers
Reset to default 11Try 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.
Try This:
function sortContacts(names, sort) {
if(sort == "ASC")
return names.sort(lastNameSort);
else
return names.sort(lastNameSortDesc);
}
//ASCENDING SORT
function lastNameSort(a,b) {
if(a.split(" ")[1] > b.split(" ")[1])
return 1;
else
return -1;
};
//DESCENDING SORT
function lastNameSortDesc(a,b) {
if(a.split(" ")[1] > b.split(" ")[1])
return -1;
else
return 1;
};
For your knowledge, the Javascript's SORT function allows us to send a "Compare" method in the parameter. In the above code, it's using the same technique.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
Bob
a first or a last name? Does theH
belong to the first or the last name? – Bergi Commented Jun 11, 2014 at 22:28