这里给出三种解决方案:
1.if条件语句 + sort()
2.localeCompare() + sort()
3.Collator() + sort()
array.sort(compareFunction)
参数 | 描述 |
---|---|
compareFunction | 可选。定义替代排序顺序的函数。该函数应返回负值、零值或正值,具体取决于参数,例如: function(a, b){ return a - b } sort() 方法比较两个值时,将值发送给比较函数,根据返的(负、零、正)值对值进行排序。举例:比较 40 和 100 时,sort() 方法调用比较函数(40,100)。该函数计算 40-100,并返回 -60(负值)。sort 函数会将 40 排序为小于 100 的值。 |
sort() 方法会改变原始数组。
Chrome、IE、Edge、Firefox、Safari、Opera 等 都支持 sort() 方法。
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var tzy = fruits.sort();
console.log(tzy);
输出如下:
var points = [66, 100, 3, 10, 250, 88, 77];
var tzy = points.sort((a, b)=> a - b);
console.log(tzy);
输出如下:
var points = [66, 100, 3, 10, 250, 88, 77];
var tzy = points.sort((a, b)=> b - a);
console.log(tzy);
输出如下:
var list = [
{ FirsName: "Aaron", LastName: "Baker" },
{ FirstName: "Bert", LastName: "Green" },
{ FirstName: "Larry", LastName: "White" },
{ FirstName: "Victor", LastName: "Fox" },
]
function sortArray(x, y) {
if (x.LastName < y.LastName) { return -1; }
if (x.LastName > y.LastName) { return 1; }
return 0;
}
var tzy = list.sort(sortArray);
console.log(tzy);
输出如下:
var list = [
{ FirsName: "Aaron", LastName: "Baker" },
{ FirstName: "Bert", LastName: "Green" },
{ FirstName: "Larry", LastName: "White" },
{ FirstName: "Victor", LastName: "Fox" },
]
function sortArray(x, y) {
return x.LastName.localeCompare(y.LastName)
}
var tzy = list.sort(sortArray);
console.log(tzy);
输出如下:
如果对象目标 key 中存在标点符号,在这种情况下,我们可以使用localeCompare()
函数并将其设置为在比较期间忽略标点符号。
var list = [
{ FirsName: "Aaron", LastName: ",Baker" },
{ FirstName: "Bert", LastName: "Green" },
{ FirstName: "Larry", LastName: ",White" },
{ FirstName: "Victor", LastName: "Fox" },
]
function SortArray(x, y){
return x.LastName.localeCompare(y.LastName, 'fr', {ignorePunctuation: true});
}
var tzy = list.sort(sortArray);
console.log(tzy);
输出如下:
你还可以通过将 localeCompare() 函数的灵敏度设置为 base 来忽略字符串中存在的特殊字符,如下所示。
x.LastName.localeCompare(y.LastName, 'en', { sensitivity: 'base' });
点击 传送门 查看有关 localeCompare()
函数的更多详细信息。
var list = [
{ FirsName: "Aaron", LastName: "Baker" },
{ FirstName: "Bert", LastName: "Green" },
{ FirstName: "Larry", LastName: "White" },
{ FirstName: "Victor", LastName: "Fox" },
]
function SortArray(x, y){
return collator.compare(x.LastName, y.LastName);
}
var tzy = list.sort(sortArray);
console.log(tzy);
输出如下: