javascript 根据嵌套值按字典顺​​序对对象数组进行排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8539934/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 03:45:45  来源:igfitidea点击:

Sort a array of objects lexicographically based on a nested value

javascriptjsonsorting

提问by Sachin

Using Javascript, I would like to know how to sort lexicographically a array of objects based on a string value in each object.

使用Javascript,我想知道如何根据每个对象中的字符串值按字典顺​​序对对象数组进行排序。

Consider:

考虑:

[
 {
    "name" : "bob",
    "count" : true
    "birthday" : 1972
 },
      {
    "name" : "jill",
    "count" : false
    "birthday" : 1922
 },
      {
    "name" : "Gerald",
    "count" : true
    "birthday" : 1920
 }
 ]

How can I sort the array alphabetically by name? The name values are usernames, so I would like to maintain the letter casing.

如何按名称的字母顺序对数组进行排序?名称值是用户名,所以我想保持字母大小写。

回答by davin

var obj = [...];

obj.sort(function(a,b){return a.name.localeCompare(b.name); });

Be aware that this will not take capitalisation into account (so it will order all names beginning with capitals before all those beginning with smalls, i.e. "Z" < "a"), so you might find it relevant to add a toUpperCase()in there.

请注意,这不会考虑大写(因此它会将所有以大写开头的名称排序在所有以小写开头的名称之前,即"Z" < "a"),因此您可能会发现toUpperCase()在其中添加 a是相关的。

You can make it more generic as well:

你也可以让它更通用:

function sortFactory(prop) {
   return function(a,b){ return a[prop].localeCompare(b[prop]); };
}

obj.sort(sortFactory('name')); // sort by name property
obj.sort(sortFactory('surname')); // sort by surname property

And even more generic if you pass the comparator to the factory...

如果您将比较器传递给工厂,则更通用......

回答by jabclab

This will do it:

这将做到:

arr.sort(function(a, b) {
    return a.name.localeCompare(b.name);
});

回答by Cesar Canassa