javascript 按键值对数组进行排序

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

Sort array on key value

javascriptarrayssortingtags

提问by Toniq

I have a function which sorts by name currently and an array of value / key pairs.

我有一个当前按名称排序的函数和一个值/键对数组。

I wonder how can I pass the key on which sort is being performed so I can call the same function every time like so:

我想知道如何传递正在执行的排序的键,以便我每次都可以像这样调用相同的函数:

var arr = [{name:'bob', artist:'rudy'},
           {name:'johhny', artist:'drusko'},
           {name:'tiff', artist:'needell'},
           {name:'top', artist:'gear'}];

sort(arr, 'name');   //trying to sort by name
sort(arr, 'artist'); //trying to sort by artist

function sort(arr) {
  arr.sort(function(a, b) {
    var nameA=a.name.toLowerCase(), nameB=b.name.toLowerCase();
    if (nameA < nameB) //sort string ascending
      return -1;
    if (nameA > nameB)
      return 1;
    return 0; //default return value (no sorting)
   });          
}

回答by Diode

Array.prototype.sortOn = function(key){
    this.sort(function(a, b){
        if(a[key] < b[key]){
            return -1;
        }else if(a[key] > b[key]){
            return 1;
        }
        return 0;
    });
}



var arr = [{name:'bob', artist:'rudy'},{name:'johhny', artist:'drusko'},{name:'tiff', artist:'needell'},{name:'top', artist:'gear'}];

arr.sortOn("name");
arr.sortOn("artist");

回答by KooiInc

Here are two sorting functions that may be useful:

这里有两个可能有用的排序函数:

// sort on values
function srt(desc) {
  return function(a,b){
   return desc ? ~~(a < b) : ~~(a > b);
  };
}

// sort on key values
function keysrt(key,desc) {
  return function(a,b){
   return desc ? ~~(a[key] < b[key]) : ~~(a[key] > b[key]);
  }
}

For your array you can sort on 'name' using:

对于您的数组,您可以使用以下方法对“名称”进行排序:

var arr = [ {name:'bob', artist:'rudy'}
           ,{name:'johhny', artist:'drusko'}
           ,{name:'tiff', artist:'needell'}
           ,{name:'top', artist:'gear'}]
          .sort(keysrt('name'));

You could also combine the sorting functions:

您还可以组合排序功能:

function srt(desc,key) {
 return function(a,b){
   return desc ? ~~(key ? a[key]<b[key] : a < b) 
               : ~~(key ? a[key] > b[key] : a > b);
  };
}

And use

并使用

var arr = [ {name:'bob', artist:'rudy'}
               ,{name:'johhny', artist:'drusko'}
               ,{name:'tiff', artist:'needell'}
               ,{name:'top', artist:'gear'}]
              .sort(srt(null,'name'));

Here's a kind of an all in one solution:

这是一种多合一的解决方案:

function srt(on,descending) {
 on = on && on.constructor === Object ? on : {};
 return function(a,b){
   if (on.string || on.key) {
     a = on.key ? a[on.key] : a;
     a = on.string ? String(a).toLowerCase() : a;
     b = on.key ? b[on.key] : b;
     b = on.string ? String(b).toLowerCase() : b;
     // if key is not present, move to the end 
     if (on.key && (!b || !a)) {
      return !a && !b ? 1 : !a ? 1 : -1;
     }
   }
   return descending ? ~~(on.string ? b.localeCompare(a) : a < b)
                     : ~~(on.string ? a.localeCompare(b) : a > b);
  };
}
// usage examples
'a,z,x,y,a,b,B,Z,a,i,j,y'.split(',').sort( srt({string:true;}) );
 //=> ,a,a,b,B,i,j,x,y,y,z,Z
[100,7,8,2,2,0,5,1,6,5,-1].sort( srt() );
 //=> -1,0,1,2,2,5,5,6,7,8,100
[100,7,8,2,2,0,5,1,6,5,-1].sort( srt({},true}) );
 //=> 100,8,7,6,5,5,2,2,1,0,-1
var objarr = 
 [ {name:'bob', artist:'rudy'}
  ,{name:'Johhny', artist:'drusko'}
  ,{name:'Tiff', artist:'needell'}
  ,{name:'top', artist:'gear'}]
 .sort( srt({key:'name',string:true}, true) );
for (var i=0;i<objarr.length;i+=1) {
  console.log(objarr[i].name);
}
//=> logs zeb, top, Tiff, Johnny consecutively

回答by Phaedrus

function keysrt(key) {
  return function(a,b){
   if (a[key] > b[key]) return 1;
   if (a[key] < b[key]) return -1;
   return 0;
  }
}

someArrayOfObjects.sort(keysrt('text'));

回答by Michael Guild

Make your life easy and use a closure https://stackoverflow.com/a/31846142/1001405

让您的生活更轻松并使用闭包 https://stackoverflow.com/a/31846142/1001405

You can see the working example here

您可以在此处查看工作示例

var filter = 'name', //sort by name
data = [{name:'bob', artist:'rudy'},{name:'johhny', artist:'drusko'},{name:'tiff', artist:'needell'},{name:'top', artist:'gear'}];; 

var compare = function (filter) {
    return function (a,b) { //closure
        var a = a[filter],
            b = b[filter];

        if (a < b) {
            return -1;
        }else if (a > b) {
            return 1;
        } else {
            return 0;
        }
    };
};

filter = compare(filter); //set filter

console.log(data.sort(filter));

回答by Jake

Looking at all the answers, I came up with my own solution that works cross-browser. The accepted solution does not work in IE or Safari. Also, the other solutions do not allow for sorting by descending.

查看所有答案,我想出了自己的跨浏览器解决方案。已接受的解决方案在 IE 或 Safari 中不起作用。此外,其他解决方案不允许按降序排序。

/*! FUNCTION: ARRAY.KEYSORT(); **/
Array.prototype.keySort = function(key, desc){
  this.sort(function(a, b) {
    var result = desc ? (a[key] < b[key]) : (a[key] > b[key]);
    return result ? 1 : -1;
  });
  return this;
}

var arr = [{name:'bob', artist:'rudy'}, {name:'johhny', artist:'drusko'}, {name:'tiff', artist:'needell'}, {name:'top', artist:'gear'}];
arr.keySort('artist');
arr.keySort('artist', true);