[英]Javascript Array sort by last name, first name
I have the following array in JavaScript, I need to sort them by last name. 我在JavaScript中有以下数组,我需要按姓氏对它们进行排序。
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: 尝试这个:
function compare(a, b) {
var splitA = a.split(" ");
var splitB = b.split(" ");
var lastA = splitA[splitA.length - 1];
var lastB = splitB[splitB.length - 1];
if (lastA < lastB) return -1;
if (lastA > lastB) return 1;
return 0;
}
var names = ["John H Newman", "Jenny Craig", "Kelly Young", "Bob"];
var sorted = names.sort(compare);
console.log(sorted);
function lastNameSort(a,b) {
return a.split(" ").pop()[0] > b.split(" ").pop()[0]
};
names.sort(lastNameSort);
This was inspired by this answer . 这是受这个答案的启发。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.