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


当前回答

我遇到了排序对象数组的问题,改变了值的优先级。基本上,我想按年龄,然后按姓氏,或者仅仅按姓氏,名字来对一系列人进行排序。

我认为与其他答案相比,这是最简单的解决方案。

它用于调用sortPeoples(['array','of','properties'],reverse=false)。

///////////////////////人群示例阵列///////////////////////var人民=[{姓名:“Zach”,姓:“Emergency”,年龄:1},{姓名:“南希”,姓:“护士”,年龄:1岁},{姓名:“Ethel”,姓:“Emergency”,年龄:1},{姓名:“尼娜”,姓:“护士”,年龄:42岁},{姓名:“Anthony”,姓:“Emergency”,年龄:42岁},{姓名:“尼娜”,姓:“护士”,年龄:32岁},{姓名:“Ed”,姓:“Emergency”,年龄:28岁},{姓名:“彼得”,姓:“医生”,年龄:58岁},{姓名:“Al”,姓:“Emergency”,年龄:58岁},{姓名:“Ruth”,姓:“Registration”,年龄:62岁},{姓名:“Ed”,姓:“Emergency”,年龄:38岁},{姓名:“Tammy”,姓:“Triage”,年龄:29岁},{姓名:“Alan”,姓:“Emergency”,年龄:60岁},{姓名:“尼娜”,姓:“护士”,年龄:58岁}];////////////////////////排序功能/////////////////////函数sortPeoples(propertyArr,reverse){函数比较(a,b){变量i=0;while(propertyArr[i]){如果(a[propertyArr[i]]<b[propertyAr[i]])返回-1;如果(a[propertyArr[i]]>b[propertyAr[i]])返回1;i++;}返回0;}人民。排序(比较);if(反向){peoples.reverse();}};////////////////排序方法结束///////////////函数printPeoples(){$(“#输出”).html(“”);people.forEach(功能(人){$('#output').append(person.surname+“”+person.name+““”+person.age+“<br>”);})}<head><script src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js“></script></head><html><body><button onclick=“sortPeoples(['surname']);printPeoples()”>仅按姓氏ASC排序会导致同名案例的混乱</button><br><button onclick=“sortPeoples(['surname','name],true);printPeoples()”>按姓氏排序,然后按名称DESC</button><br><button onclick=“sortPeoples(['age']);printPeoples()”>按age ASC排序。与第一种情况相同的问题</button><br><button onclick=“sortPeoples(['age','姓']);printPeoples()”>按age和姓氏ASC排序。添加第二个字段修复了它。</button><br><div id=“output”></div></body></html>

其他回答

示例用法:

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 compare( a, b ) {
  if ( a.last_nom < b.last_nom ){
    return -1;
  }
  if ( a.last_nom > b.last_nom ){
    return 1;
  }
  return 0;
}

objs.sort( compare );

或内联(由Marco Demaio转交):

objs.sort((a,b) => (a.last_nom > b.last_nom) ? 1 : ((b.last_nom > a.last_nom) ? -1 : 0))

或简化为数字(由Andre Figueiredo转交):

objs.sort((a,b) => a.last_nom - b.last_nom); // b - a for reverse sort

如果您有嵌套对象

const objs = [{
        first_nom: 'Lazslo',
        last_nom: 'Jamf',
        moreDetails: {
            age: 20
        }
    }, {
        first_nom: 'Pig',
        last_nom: 'Bodine',
        moreDetails: {
            age: 21
        }
    }, {
        first_nom: 'Pirate',
        last_nom: 'Prentice',
        moreDetails: {
            age: 22
        }
    }];

nestedSort = (prop1, prop2 = null, direction = 'asc') => (e1, e2) => {
        const a = prop2 ? e1[prop1][prop2] : e1[prop1],
            b = prop2 ? e2[prop1][prop2] : e2[prop1],
            sortOrder = direction === "asc" ? 1 : -1
        return (a < b) ? -sortOrder : (a > b) ? sortOrder : 0;
    }

并称之为

objs.sort(nestedSort("last_nom"));
objs.sort(nestedSort("last_nom", null, "desc"));
objs.sort(nestedSort("moreDetails", "age"));
objs.sort(nestedSort("moreDetails", "age", "desc"));
let propName = 'last_nom';

let sorted_obj = objs.sort((a,b) => {
    if(a[propName] > b[propName]) {
        return 1;
    }
    if (a[propName] < b[propName]) {
        return -1;
    }
    return 0;
}

//This works because the js built-in sort function allows us to define our
//own way of sorting, this funny looking function is simply telling `sort` how to
//determine what is larger. 
//We can use `if(a[propName] > b[propName])` because string comparison is already built into JS
//if you try console.log('a' > 'z' ? 'a' : 'z')
//the output will be 'z' as 'a' is not greater than 'z'
//The return values 0,-1,1 are how we tell JS what to sort on. We're sorting on the last_nom property of the object. 
//When sorting a list it comes down to comparing two items and how to determine which one of them is "larger". 
//We need a way to tell JS how to determine which one is larger. 
//The sort defining function will use the case that returns a 1 to mean that a > b
//and the case that returns -1 to mean that a < b

根据您的示例,您需要按两个字段(姓、名)排序,而不是一个。您可以使用Alasql库在一行中进行排序:

var res = alasql('SELECT * FROM ? ORDER BY last_nom, first_nom',[objs]);

在JSFiddle中尝试此示例。