假设您有一个 JavaScript 数组 包含星际迷航:下一代字符

const characters = [
  { firstName: Jean-Luc, lastName: Picard, rank: Captain, age: 59 },
  { firstName: Will, lastName: Riker, rank: Commander, age: 29 },
  { firstName: Geordi, lastName: La Forge, rank: Lieutenant, age: 29 }
];

你如何按不同的属性对这个数组进行排序?

排序依据 age

JavaScript 的内置 Array#sort() 函数 可选地采用一个 回调 参数来比较数组中的两个元素。

回调函数被调用 compareFunction(),如果 compareFunction(a, b) 返回一个值为 < 0,JavaScript 认为 a 小于 b
而如果 compareFunction(a, b) 返回一个值为 > 0,JavaScript 认为 b 大于 a

这意味着很容易按数字属性进行排序,例如 age,如果 a.age - b.age < 0,这意味着 ba

const characters = [
  { firstName: Jean-Luc, lastName: Picard, rank: Captain, age: 59 },
  { firstName: Will, lastName: Riker, rank: Commander, age: 29 },
  { firstName: Geordi, lastName: La Forge, rank: Lieutenant, age: 29 }
];

characters.sort((a, b) => a.age - b.age);

// Riker, La Forge, Picard
characters;

排序依据 lastName

按字符串属性排序,例如 lastName 也很容易,因为 JavaScript 的 <> 属性可以处理字符串。 要按字符串属性排序,您的 compareFunction() 可以使用比较两个字符串 <

const characters = [
  { firstName: Jean-Luc, lastName: Picard, rank: Captain, age: 59 },
  { firstName: Will, lastName: Riker, rank: Commander, age: 29 },
  { firstName: Geordi, lastName: La Forge, rank: Lieutenant, age: 29 }
];

characters.sort((a, b) => {
  if (a === b) {
    return 0;
  }
  return a.lastName < b.lastName ? -1 : 1;
});

// La Forge, Picard, Riker
characters;

排序依据 rank

排序依据 rank 有点棘手,因为排名不一定按字母顺序排列。 JavaScript 不知道 Captain 的级别高于 Lieutenant。

要按自定义排序排序,您应该定义一个地图 rank 为数值,以便于比较。

const characters = [
  { firstName: Jean-Luc, lastName: Picard, rank: Captain, age: 59 },
  { firstName: Will, lastName: Riker, rank: Commander, age: 29 },
  { firstName: Geordi, lastName: La Forge, rank: Lieutenant, age: 29 }
];

const rankOrder = new Map([
  [Captain, 1],
  [Commander, 2],
  [Lieutenant, 3]
]);

characters.sort((a, b) => {
  return rankOrder.get(a.rank) - rankOrder.get(b.rank);
});

// Picard, Riker, La Forge
characters;
© 版权声明
评论 抢沙发

请登录后发表评论