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


当前回答

使用JavaScript排序方法

排序方法可以修改为使用比较函数对数字、字符串甚至对象数组进行排序。

比较函数作为可选参数传递给排序方法。

此比较函数接受两个参数,通常称为a和b。根据这两个参数可以修改排序方法,使其按需工作。

如果compare函数返回的值小于0,那么sort()方法将a排序到比b低的索引。如果compare函数返回的值等于0,那么sort()方法将保持元素位置不变。如果compare函数返回的值大于0,那么sort()方法会以大于b的索引对a进行排序。

使用上述概念应用于对象,其中a将是对象属性。

var对象=[{first_nom:'Lazslo',last_nom:'Jamf'},{first_nom:'猪',last_nom:'Bodine'},{first_nom:'海盗',last_nom:'Prentice'}];函数比较(a,b){如果(a.last_nom>b.last_nom)返回1;如果(a.last_nom<b.last_nom)返回-1;返回0;}objs.sort(比较);console.log(对象)//要获得更好的外观,请使用console.table(objs)

其他回答

使用JavaScript排序方法

排序方法可以修改为使用比较函数对数字、字符串甚至对象数组进行排序。

比较函数作为可选参数传递给排序方法。

此比较函数接受两个参数,通常称为a和b。根据这两个参数可以修改排序方法,使其按需工作。

如果compare函数返回的值小于0,那么sort()方法将a排序到比b低的索引。如果compare函数返回的值等于0,那么sort()方法将保持元素位置不变。如果compare函数返回的值大于0,那么sort()方法会以大于b的索引对a进行排序。

使用上述概念应用于对象,其中a将是对象属性。

var对象=[{first_nom:'Lazslo',last_nom:'Jamf'},{first_nom:'猪',last_nom:'Bodine'},{first_nom:'海盗',last_nom:'Prentice'}];函数比较(a,b){如果(a.last_nom>b.last_nom)返回1;如果(a.last_nom<b.last_nom)返回-1;返回0;}objs.sort(比较);console.log(对象)//要获得更好的外观,请使用console.table(objs)

它对我有用。在这里,它将一直保持未定义状态。

函数排序(项、属性、方向){函数比较(a,b){if(!a[property]&&!b[property]){返回0;}否则如果(a[property]&&!b[property]){返回-1;}否则如果(!a[property]&&b[property]){返回1;}其他{const value1=a[property].toString().toUpperCase();//忽略大小写const value2=b[property].toString().toUpperCase();//忽略大小写如果(值1<值2){返回方向==0-1 : 1;}否则如果(值1>值2){返回方向==0?1 : -1;}其他{返回0;}}}返回项目。排序(比较);} 变量项=[{名称:'Edward',值:21},{name:“Sharpe”,值:37},{name:“And”,值:45},{name:“The”,值:-12},{名称:未定义,值:-12},{name:“Magnetic”,值:13},{name:“Zeros”,值:37}];console.log('场景顺序:-');console.log(排序(项,'name',0));console.log('下订单:-');console.log(排序(项,'name',1));

编写短代码:

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

尝试以下方式:

let objs = [
        { first_nom: 'Lazslo', last_nom: 'Jamf'     },
        { first_nom: 'Pig',    last_nom: 'Bodine'   },
        { first_nom: 'Pirate', last_nom: 'Prentice' }
    ];

const compareBylastNom = (a, b) => {
    // Converting to uppercase to have case-insensitive comparison
    const name1 = a.last_nom.toUpperCase();
    const name2 = b.last_nom.toUpperCase();

    let comparison = 0;

    if (name1 > name2) {
        comparison = 1;
    } else if (name1 < name2) {
        comparison = -1;
    }
    return comparison;
}

console.log(objs.sort(compareBylastNom));

我没有看到任何类似于我的实现。此版本基于施瓦茨变换习惯用法。

function sortByAttribute(array, ...attrs) {
  // Generate an array of predicate-objects containing
  // property getter, and descending indicator
  let predicates = attrs.map(pred => {
    let descending = pred.charAt(0) === '-' ? -1 : 1;
    pred = pred.replace(/^-/, '');
    return {
      getter: o => o[pred],
      descend: descending
    };
  });
  // Schwartzian transform idiom implementation. AKA "decorate-sort-undecorate"
  return array.map(item => {
    return {
      src: item,
      compareValues: predicates.map(predicate => predicate.getter(item))
    };
  })
  .sort((o1, o2) => {
    let i = -1, result = 0;
    while (++i < predicates.length) {
      if (o1.compareValues[i] < o2.compareValues[i])
        result = -1;
      if (o1.compareValues[i] > o2.compareValues[i])
        result = 1;
      if (result *= predicates[i].descend)
        break;
    }
    return result;
  })
  .map(item => item.src);
}

下面是如何使用它的示例:

let games = [
  { name: 'Mashraki',          rating: 4.21 },
  { name: 'Hill Climb Racing', rating: 3.88 },
  { name: 'Angry Birds Space', rating: 3.88 },
  { name: 'Badland',           rating: 4.33 }
];

// Sort by one attribute
console.log(sortByAttribute(games, 'name'));
// Sort by mupltiple attributes
console.log(sortByAttribute(games, '-rating', 'name'));