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


当前回答

简单答案:

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

细节:

今天非常简单,您可以将字符串与localeCompare进行比较。正如Mozilla Doc所说:

localeCompare()方法返回一个数字,指示引用字符串在排序顺序上位于给定字符串之前、之后或与给定字符串相同。

    //example1:
    console.log("aaa".localeCompare("aab")); //-1
    console.log("aaa".localeCompare("aaa")); //0
    console.log("aab".localeCompare("aaa")); //1

    //example2:
    const a = 'réservé'; // with accents, lowercase
    const b = 'RESERVE'; // no accents, uppercase

    console.log(a.localeCompare(b));
    // expected output: 1
    console.log(a.localeCompare(b, 'en', { sensitivity: 'base' }));
    // expected output: 0

有关详细信息,请参阅Mozilla doclocaleCompare:

其他回答

示例用法:

objs.sort(sortBy('last_nom'));

脚本:

/**
 * @description
 * Returns a function which will sort an
 * array of objects by the given key.
 *
 * @param  {String}  key
 * @param  {Boolean} reverse
 * @return {Function}
 */
const sortBy = (key, reverse) => {

  // Move smaller items towards the front
  // or back of the array depending on if
  // we want to sort the array in reverse
  // order or not.
  const moveSmaller = reverse ? 1 : -1;

  // Move larger items towards the front
  // or back of the array depending on if
  // we want to sort the array in reverse
  // order or not.
  const moveLarger = reverse ? -1 : 1;

  /**
   * @param  {*} a
   * @param  {*} b
   * @return {Number}
   */
  return (a, b) => {
    if (a[key] < b[key]) {
      return moveSmaller;
    }
    if (a[key] > b[key]) {
      return moveLarger;
    }
    return 0;
  };
};

这里有一个函数,您可以使用它按多个对象对列表进行排序,如果第一个对象相等,则第二个顺序将用作回退。如果可能的话,空值也应忽略到回退顺序。

function sortObjects(list, orderBy){
    list.sort(function(a, b){
        let byIndex = 0;
        let order = orderBy[byIndex];
        while(!a[order.by] || !b[order.by] || a[order.by] === b[order.by]){
            byIndex++;
            if(byIndex >= orderBy.length){break;}
            order = orderBy[byIndex];
        }
        if(!a[order.by] || !b[order.by] || a[order.by] === b[order.by]){
            return false;
        }
        if(order.desc){
            return a[order.by] < b[order.by];
        }
        return a[order.by] > b[order.by];
    });
    return list;
}

用法:

var objs = [
    {a: 10, b: 20, c: 30},
    {a: 30, b: 10, c: 20},
    {a: 20, b: 10, c: 30},
];

sortObjectList(objs, [{by: 'a'}]);
[
    {a: 10, b: 20, c: 30},
    {a: 20, b: 10, c: 30},
    {a: 30, b: 10, c: 20},
]

sortObjectList(objs, [{by: 'a', desc: true}]);
[
    {a: 30, b: 10, c: 20},
    {a: 20, b: 10, c: 30},
    {a: 10, b: 20, c: 30},
]

sortObjectList(objs, [{by: 'b', desc: true}, {by: 'c'}]);
[
    {a: 10, b: 20, c: 30},
    {a: 30, b: 10, c: 20},
    {a: 20, b: 10, c: 30},
]

另一个例子:

var objs = [
    {a: 5, b: 5},
    {a: 10, b: 15},
    {a: 15, b: 25},
    {b: 10},
    {b: 20},
    {a: 10, b: 30},
    {a: 10, b: 12},
];

sortObjectList(objs, [{by: 'a'}, {by: 'b'}]);
[
    {a: 5, b: 5},
    {b: 10},
    {a: 10, b: 12},
    {a: 10, b: 15},
    {b: 20},
    {a: 10, b: 30},
    {a: 15, b: 25},
]

将Ege的动态解决方案与Vinay的想法相结合,您可以得到一个很好的鲁棒解决方案:

Array.prototype.sortBy=函数(){函数_sortByAttr(属性){var sortOrder=1;如果(属性[0]==“-”){sortOrder=-1;attr=attr.substr(1);}返回函数(a,b){var结果=(a[attr]<b[attr])-1:(a[attr]>b[attr])?1 : 0;返回结果*sortOrder;}}函数_getSortFunc(){if(arguments.length==0){throw“Array.sortBy()不允许零长度参数”;}var args=参数;返回函数(a,b){for(var result=0,i=0;result==0&&i<args.length;i++){result=_sortByAttr(args[i])(a,b);}返回结果;}}返回this.sort(_getSortFunc.apply(null,arguments));}用法://用于打印对象的实用程序Array.prototype.print=函数(标题){console.log(“************************************************************”);console.log(“***”+标题);console.log(“************************************************************”);对于(var i=0;i<this.length;i++){console.log(“名称:”+此[i].FirstName,此[i].LastName,“年龄:”+该[i].Age);}}//设置示例数据变量arrObj=[{名字:“Zach”,姓氏:“Emergency”,年龄:35岁},{名字:“Nancy”,姓氏:“护士”,年龄:27岁},{名字:“Ethel”,姓氏:“Emergency”,年龄:42岁},{名字:“Nina”,姓氏:“护士”,年龄:48岁},{名字:“Anthony”,姓氏:“Emergency”,年龄:44岁},{名字:“Nina”,姓氏:“护士”,年龄:32岁},{名字:“Ed”,姓氏:“Emergency”,年龄:28岁},{名字:“Peter”,姓氏:“医生”,年龄:58岁},{名字:“Al”,姓氏:“Emergency”,年龄:51岁},{名字:“Ruth”,姓氏:“注册”,年龄:62岁},{名字:“Ed”,姓氏:“Emergency”,年龄:38岁},{名字:“Tammy”,姓氏:“Triage”,年龄:29岁},{名字:“Alan”,姓氏:“Emergency”,年龄:60岁},{名字:“Nina”,姓氏:“护士”,年龄:54岁}];//单元测试arrObj.sortBy(“姓氏”).print(“姓氏升序”);arrObj.sortBy(“-姓氏”).print(“姓氏降序”);arrObj.sortBy(“姓氏”、“名字”、“年龄”).print(“姓氏升序、名字升序、年龄降序”);arrObj.sortBy(“-FirstName”,“Age”).print(“FirstName降序,Age升序”);arrObj.sortBy(“-Age”).print(“Age Descending”);

方式1:

您可以使用Undercore.js。首先导入下划线。

 import * as _ from 'underscore';
 let SortedObjs = _.sortBy(objs, 'last_nom');

方法2:使用比较函数。

function compare(first, second) {
     if (first.last_nom < second.last_nom)
         return -1;
     if (first.last_nom > second.last_nom)
       return 1;
    return 0;
 }

objs.sort(compare);

当您需要自然排序(即1,2,10,111111)时,使用Intl.Collator对特定情况的对象进行排序。

常量文件=[{name:“1.mp3”,大小:123},{name:“10.mp3”,大小:456},{name:“100.mp3”,大小:789},{name:“11.mp3”,大小:123},{name:“111.mp3”,大小:456},{name:“2.mp3”,大小:789},];const naturalCollator=新Intl.Collator(未定义,{numeric:true,sensitity:'base'});files.sort((a,b)=>naturalCollator.compare(a.name,b.name));console.log(文件);

浏览器支持Intl.Collator