Javascript 对对象数组进行排序的简单函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8175093/
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-08-24 04:58:38  来源:igfitidea点击:

Simple function to sort an array of objects

javascriptsorting

提问by John

I would like to create a (non-anonymous) function that sorts an array of objects alphabetically by the key name. I only code straight-out JavaScript so frameworks don't help me in the least.

我想创建一个(非匿名)函数,该函数按 key 的字母顺序对对象数组进行排序name。我只编写直接的 JavaScript,所以框架至少对我没有帮助。

var people = [
    {'name': 'a75', 'item1': false, 'item2': false},
    {'name': 'z32', 'item1': true,  'item2': false},
    {'name': 'e77', 'item1': false, 'item2': false}
];

回答by David Brainer

How about this?

这个怎么样?

var people = [
{
    name: 'a75',
    item1: false,
    item2: false
},
{
    name: 'z32',
    item1: true,
    item2: false
},
{
    name: 'e77',
    item1: false,
    item2: false
}];

function sort_by_key(array, key)
{
 return array.sort(function(a, b)
 {
  var x = a[key]; var y = b[key];
  return ((x < y) ? -1 : ((x > y) ? 1 : 0));
 });
}

people = sort_by_key(people, 'name');

This allows you to specify the key by which you want to sort the array so that you are not limited to a hard-coded name sort. It will work to sort any array of objects that all share the property which is used as they key. I believe that is what you were looking for?

这允许您指定要用来对数组进行排序的键,这样您就不受限于硬编码的名称排序。它将对所有共享用作它们的键的属性的任何对象数组进行排序。我相信这就是你要找的?

And here is a jsFiddle: http://jsfiddle.net/6Dgbu/

这是一个 jsFiddle:http: //jsfiddle.net/6Dgbu/

回答by pimvdb

You can sort an array([...]) with the .sortfunction:

您可以使用以下函数对数组( [...]) 进行排序.sort

var people = [
    {'name': 'a75', 'item1': false, 'item2': false},
    {'name': 'z32', 'item1': true,  'item2': false},
    {'name': 'e77', 'item1': false, 'item2': false},
];

var sorted = people.sort(function IHaveAName(a, b) { // non-anonymous as you ordered...
    return b.name < a.name ?  1 // if b should come earlier, push a to end
         : b.name > a.name ? -1 // if b should come later, push a to begin
         : 0;                   // a and b are equal
});

回答by Geuis

This isn't a JSON question, per se. Its a javascript array question.

这本身不是一个 JSON 问题。它是一个 javascript 数组问题。

Try this:

尝试这个:

people.sort(function(a,b){ 
    var x = a.name < b.name? -1:1; 
    return x; 
});

回答by Nate Getch

My solution for similar sort problem using ECMA 6

我使用 ECMA 6 解决类似排序问题

var library = [
        {name: 'Steve', course:'WAP', courseID: 'cs452'}, 
        {name: 'Rakesh', course:'WAA', courseID: 'cs545'},
        {name: 'Asad', course:'SWE', courseID: 'cs542'},
];

const sorted_by_name = library.sort( (a,b) => a.name > b.name );

for(let k in sorted_by_name){
    console.log(sorted_by_name[k]);
}

回答by Ryan Wibawa

I modified @Geuis 's answer by using lambda and convert it upper case first:

我通过使用 lambda 修改了 @Geuis 的答案并首先将其转换为大写:

people.sort((a, b) => a.toLocaleUpperCase() < b.toLocaleUpperCase() ? -1 : 1);

回答by aljgom

Array.prototype.sort_by = function(key_func, reverse=false){
    return this.sort( (a, b) => ( key_func(b) - key_func(a) ) * (reverse ? 1 : -1) ) 
}

Then for example if we have

然后例如如果我们有

var arr = [ {id: 0, balls: {red: 8,  blue: 10}},
            {id: 2, balls: {red: 6 , blue: 11}},
            {id: 1, balls: {red: 4 , blue: 15}} ]

arr.sort_by(el => el.id, reverse=true)
/* would result in
[ { id: 2, balls: {red: 6 , blue: 11 }},
  { id: 1, balls: {red: 4 , blue: 15 }},
  { id: 0, balls: {red: 8 , blue: 10 }} ]
*/

or

或者

arr.sort_by(el => el.balls.red + el.balls.blue)
/* would result in
[ { id: 2, balls: {red: 6 , blue: 11 }},    // red + blue= 17
  { id: 0, balls: {red: 8 , blue: 10 }},    // red + blue= 18
  { id: 1, balls: {red: 4 , blue: 15 }} ]   // red + blue= 19
*/

回答by iknowsomething

var data = [ 1, 2, 5, 3, 1]; data.sort(function(a,b) { return a-b });

var data = [ 1, 2, 5, 3, 1]; data.sort(function(a,b) { return a-b });

With a small compartor and using sort, we can do it

使用一个小的比较器并使用排序,我们可以做到

回答by muhammad tayyab

This is how simply I sort from previous examples:

这就是我从前面的例子中排序的简单方式:

if my array is items:

如果我的数组是items

0: {id: 14, auctionID: 76, userID: 1, amount: 39}
1: {id: 1086, auctionID: 76, userID: 1, amount: 55}
2: {id: 1087, auctionID: 76, userID: 1, amount: 55}

I thought simply calling items.sort()would sort it it, but there was two problems: 1. Was sorting them strings 2. Was sorting them first key

我以为只需调用items.sort()就可以对其进行排序,但是有两个问题: 1. 是否对字符串进行排序 2. 是否将它们排序为第一个键

This is how I modified the sort function:

这是我修改排序函数的方式:

for(amount in items){
if(item.hasOwnProperty(amount)){

i.sort((a, b) => a.amount - b.amount);
}
}

回答by ashoka pal

var library = [
        {name: 'Steve', course:'WAP', courseID: 'cs452'}, 
        {name: 'Rakesh', course:'WAA', courseID: 'cs545'},
        {name: 'Asad', course:'SWE', courseID: 'cs542'},
];

const sorted_by_name = library.sort( (a,b) => a.name > b.name );

for(let k in sorted_by_name){
    console.log(sorted_by_name[k]);
}

回答by Brian

var people = 
[{"name": 'a75',"item1": "false","item2":"false"}, 
{"name": 'z32',"item1": "true","item2":  "false"}, 
{"name": 'e77',"item1": "false","item2": "false"}]; 

function mycomparator(a,b) {   return parseInt(a.name) - parseInt(b.name);  } 
people.sort(mycomparator); 

something along the lines of this maybe (or as we used to say, this should work).

可能与此类似的事情(或者正如我们过去所说的那样,这应该可行)。