我有一个JavaScript对象数组:
var objs = [
{ first_nom: 'Lazslo', last_nom: 'Jamf' },
{ first_nom: 'Pig', last_nom: 'Bodine' },
{ first_nom: 'Pirate', last_nom: 'Prentice' }
];
如何在JavaScript中按last_nom的值对它们进行排序?
我知道排序(a,b),但这似乎只适用于字符串和数字。是否需要向对象添加toString()方法?
一个按属性对对象数组进行排序的简单函数:
function sortArray(array, property, direction) {
direction = direction || 1;
array.sort(function compare(a, b) {
let comparison = 0;
if (a[property] > b[property]) {
comparison = 1 * direction;
} else if (a[property] < b[property]) {
comparison = -1 * direction;
}
return comparison;
});
return array; // Chainable
}
用法:
var objs = [
{ first_nom: 'Lazslo', last_nom: 'Jamf' },
{ first_nom: 'Pig', last_nom: 'Bodine' },
{ first_nom: 'Pirate', last_nom: 'Prentice' }
];
sortArray(objs, "last_nom"); // Asc
sortArray(objs, "last_nom", -1); // Desc
简单答案:
objs.sort((a,b)=>a.last_nom.localeCompare(b.last_nom))
细节:
今天非常简单,您可以将字符串与localeCompare进行比较。正如Mozilla Doc所说:
localeCompare()方法返回一个数字,指示引用字符串在排序顺序上位于给定字符串之前、之后或与给定字符串相同。
//example1:
console.log("aaa".localeCompare("aab")); //-1
console.log("aaa".localeCompare("aaa")); //0
console.log("aab".localeCompare("aaa")); //1
//example2:
const a = 'réservé'; // with accents, lowercase
const b = 'RESERVE'; // no accents, uppercase
console.log(a.localeCompare(b));
// expected output: 1
console.log(a.localeCompare(b, 'en', { sensitivity: 'base' }));
// expected output: 0
有关详细信息,请参阅Mozilla doclocaleCompare:
我将给您一个实现选择排序算法的解决方案。它简单有效。
var objs = [
{ first_nom: 'Lazslo', last_nom: 'Jamf' },
{ first_nom: 'Pig', last_nom: 'Bodine' },
{ first_nom: 'Pirate', last_nom: 'Prentice' }
];
function selection_Sort(num) {
//console.log(num);
var temp, index;
for (var i = 0; i <= num.length - 1; i++) {
index = i;
for (var j = i + 1; j <= num.length - 1; j++) {
// You can use first_nom/last_nom, any way you choose to sort
if (num[j].last_nom < num[index].last_nom) {
index = j;
}
}
// Below is the swapping part
temp = num[i].last_nom;
num[i].last_nom = num[index].last_nom;
num[index].last_nom = temp;
};
console.log(num);
return num;
}
selection_Sort(objs);
Deep
基于这篇优秀的教程,我想开发Vlad Bezden的答案,并解释为什么localeCompare优于标准比较方法,如strA>strB。让我们运行以下示例:
console.log(“Österreich”>“Zealand”);//我们期望错误console.log(“a”>“Z”);//我们期望错误
原因是在JavaScript中,所有字符串都使用UTF-16编码
让str=“”;//JavaScript中的字符顺序for(设i=65;i<=220;i++){str+=字符串.fromCodePoint(i);//代码到字符}console.log(str);
首先是大写字母(有小代码),然后是小写字母,然后是字符Ö(在z之后)。这就是为什么我们在第一个代码段中得到正确的原因,因为运算符>比较字符代码。
如您所见,比较不同语言中的字符是一项非常重要的任务,但幸运的是,现代浏览器支持国际化标准ECMA-402。所以在JavaScript中,我们有strA.localeCompare(strB)来完成任务(-1表示strA小于strB;1表示相反;0表示相等)
console.log('Österreich'.localeCompare('Zealand'));//我们期望-1console.log('a'.localeCompare('Z'));//我们期望-1
我想补充一点,localeCompare支持两个参数:语言和其他规则:
var对象=[{first_nom:'Lazslo',last_nom:'Jamf'},{first_nom:'猪',last_nom:'Bodine'},{first_nom:'海盗',last_nom:'Prentice'},{first_nom:'测试',last_nom:'jamf'}];objs.sort((a,b)=>a.last_nom.localeCompare(b.last_nom,'en',{sensitity:'case'}))console.log(objs);//在'>'比较中,'Jamf'不会在'Jamf'旁边