Jef*_*ick 7 javascript arrays sorting
我在JavaScript中有以下数组,我需要按姓氏对它们进行排序.
var names = [Jenny Craig, John H Newman, Kelly Young, Bob];
Run Code Online (Sandbox Code Playgroud)
结果将是:
Bob,
Jenny Craig,
John H Newman,
Kelly Young
Run Code Online (Sandbox Code Playgroud)
有关如何执行此操作的任何示例?
试试这个:
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);
Run Code Online (Sandbox Code Playgroud)
这是一个小提琴.