我有一个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()方法?
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'旁边
尝试以下方式:
let objs = [
{ first_nom: 'Lazslo', last_nom: 'Jamf' },
{ first_nom: 'Pig', last_nom: 'Bodine' },
{ first_nom: 'Pirate', last_nom: 'Prentice' }
];
const compareBylastNom = (a, b) => {
// Converting to uppercase to have case-insensitive comparison
const name1 = a.last_nom.toUpperCase();
const name2 = b.last_nom.toUpperCase();
let comparison = 0;
if (name1 > name2) {
comparison = 1;
} else if (name1 < name2) {
comparison = -1;
}
return comparison;
}
console.log(objs.sort(compareBylastNom));
下划线.js
使用Undercore.js]。它很小,非常棒。。。
sortBy_.sortBy(列表,迭代器,[context])返回列表,按运行每个值的结果升序排列通过迭代器。迭代器也可以是属性的字符串名称按(例如长度)排序。
var objs = [
{ first_nom: 'Lazslo',last_nom: 'Jamf' },
{ first_nom: 'Pig', last_nom: 'Bodine' },
{ first_nom: 'Pirate', last_nom: 'Prentice' }
];
var sortedObjs = _.sortBy(objs, 'first_nom');