我有一个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()方法?


当前回答

给定原始示例:

var objs = [ 
    { first_nom: 'Lazslo', last_nom: 'Jamf'     },
    { first_nom: 'Pig',    last_nom: 'Bodine'   },
    { first_nom: 'Pirate', last_nom: 'Prentice' }
];

按多个字段排序:

objs.sort(function(left, right) {
    var last_nom_order = left.last_nom.localeCompare(right.last_nom);
    var first_nom_order = left.first_nom.localeCompare(right.first_nom);
    return last_nom_order || first_nom_order;
});

笔记

a.localeCompare(b)是普遍支持的,如果a<b,a==b,a>b,则分别返回-1,0,1。||在最后一行中,last_nom优先于first_nom。减法适用于数字字段:var age_order=left.age-right.age;取反顺序,返回-last_nom_order | |-first_nom_oorder | |-age_order;

其他回答

我知道已经有很多答案了,包括那些带有localeCompare的答案,但如果您出于某种原因不想/不能使用localeCompae,我建议您使用此解决方案,而不是三元运算符解决方案:

objects.sort((a, b) => (a.name > b.name) - (a.name < b.name));

有人可能会说,这段代码在做什么并不明显,但在我看来,三元运算符更糟糕。如果一个三元运算符足够可读,那么两个三元操作符一个嵌入另一个-真的很难读而且很难看。只有两个比较运算符和一个减号运算符的单行代码非常容易阅读,因此很容易推理。

这里有很多好的答案,但我想指出,它们可以非常简单地扩展,以实现更复杂的排序。您必须做的唯一一件事就是使用OR运算符来链接比较函数,如下所示:

objs.sort((a,b)=> fn1(a,b) || fn2(a,b) || fn3(a,b) )

其中fn1,fn2。。。是返回[-1,0,1]的排序函数。这导致“按fn1排序”和“按fn2排序”,这在SQL中相当于ORDERBY。

此解决方案基于||运算符的行为,该运算符的求值结果为第一个可转换为true的求值表达式。

最简单的表单只有一个这样的内联函数:

// ORDER BY last_nom
objs.sort((a,b)=> a.last_nom.localeCompare(b.last_nom) )

使用last_nom和first_nom排序顺序有两个步骤,如下所示:

// ORDER_BY last_nom, first_nom
objs.sort((a,b)=> a.last_nom.localeCompare(b.last_nom) ||
                  a.first_nom.localeCompare(b.first_nom)  )

通用比较函数可以是这样的:

// ORDER BY <n>
let cmp = (a,b,n)=>a[n].localeCompare(b[n])

此函数可以扩展为支持数字字段、区分大小写、任意数据类型等。

您可以通过按排序优先级链接它们来使用它们:

// ORDER_BY last_nom, first_nom
objs.sort((a,b)=> cmp(a,b, "last_nom") || cmp(a,b, "first_nom") )
// ORDER_BY last_nom, first_nom DESC
objs.sort((a,b)=> cmp(a,b, "last_nom") || -cmp(a,b, "first_nom") )
// ORDER_BY last_nom DESC, first_nom DESC
objs.sort((a,b)=> -cmp(a,b, "last_nom") || -cmp(a,b, "first_nom") )

这里的重点是,采用函数方法的纯JavaScript可以在没有外部库或复杂代码的情况下走很长的路。它也非常有效,因为不需要进行字符串解析。

它对我有用。在这里,它将一直保持未定义状态。

函数排序(项、属性、方向){函数比较(a,b){if(!a[property]&&!b[property]){返回0;}否则如果(a[property]&&!b[property]){返回-1;}否则如果(!a[property]&&b[property]){返回1;}其他{const value1=a[property].toString().toUpperCase();//忽略大小写const value2=b[property].toString().toUpperCase();//忽略大小写如果(值1<值2){返回方向==0-1 : 1;}否则如果(值1>值2){返回方向==0?1 : -1;}其他{返回0;}}}返回项目。排序(比较);} 变量项=[{名称:'Edward',值:21},{name:“Sharpe”,值:37},{name:“And”,值:45},{name:“The”,值:-12},{名称:未定义,值:-12},{name:“Magnetic”,值:13},{name:“Zeros”,值:37}];console.log('场景顺序:-');console.log(排序(项,'name',0));console.log('下订单:-');console.log(排序(项,'name',1));

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'旁边

您可以使用最简单的方式:Lodash

(https://lodash.com/docs/4.17.10#orderBy)

此方法类似于_.sortBy,只是它允许指定要排序的迭代项的排序顺序。如果未指定顺序,则所有值都按升序排序。否则,为相应值的降序指定“desc”,为升序指定“asc”。

论据

collection(Array | Object):要迭代的集合。[iteratees=[_.identity]](数组[]|函数[]|对象[]|字符串[]):要排序的iterates。[orders](string[]):迭代的排序顺序。

退换商品

(Array):返回新的排序数组。


var _ = require('lodash');
var homes = [
    {"h_id":"3",
     "city":"Dallas",
     "state":"TX",
     "zip":"75201",
     "price":"162500"},
    {"h_id":"4",
     "city":"Bevery Hills",
     "state":"CA",
     "zip":"90210",
     "price":"319250"},
    {"h_id":"6",
     "city":"Dallas",
     "state":"TX",
     "zip":"75000",
     "price":"556699"},
    {"h_id":"5",
     "city":"New York",
     "state":"NY",
     "zip":"00010",
     "price":"962500"}
    ];
    
_.orderBy(homes, ['city', 'state', 'zip'], ['asc', 'desc', 'asc']);