数组、对象和对象数组的字母排序

Avatar of Chris Coyier
Chris Coyier

一个数组

let fruits = [`bananas`, `Apples`, `Oranges`];

你可以很容易地对它进行字母排序,例如

fruits.sort();

但是请注意数组中大小写不一致的情况……大写字符将全部排序在小写字符之前(很奇怪),因此会稍微复杂一些

let fruits = [`bananas`, `Apples`, `Oranges`];
fruits.sort((a, b) => {
  return a.toLowerCase().localeCompare(b.toLowerCase());
})
console.log(fruits);

// ["Apples", "bananas", "Oranges"]

对象数组

如果你要排序的内容嵌套在对象中,事情会变得更加棘手。在使用 JSON API 时很容易出现这种情况。

let fruits = [
  {
    fruit: `Bananas`
  },
  {
    fruit: `apples`
  },
  {
    fruit: `Oranges`
  }
];

我们可以为此创建一个自定义排序函数,但更进一步的是创建一个更通用的函数,该函数将要排序的键作为参数。

const propComparator = (propName) =>
  (a, b) => a[propName].toLowerCase() == b[propName].toLowerCase() ? 0 : a[propName].toLowerCase() < b[propName].toLowerCase() ? -1 : 1

所以现在我们可以用它来排序

fruits.sort(propComparator(`fruit`));
console.log(fruits);

/*
[
  {fruit: "apples"},
  {fruit: "Bananas"},
  {fruit: "Oranges"}
]
*/

只是一个对象

如果我们只有一个对象……

let fruits = {
  Bananas: true,
  apples: false,
  Oranges: true
};

我们仍然需要将这些键转换为小写,但我们可以对键的数组进行排序,然后从这个新排序的键数组创建一个新对象。

let sortedFruits = {};
Object.keys(fruits).sort((a, b) => {
  return a.toLowerCase().localeCompare(b.toLowerCase());
}).forEach(function(key) {
  sortedFruits[key] = fruits[key];
});
console.log(sortedFruits);

/*
{
  apples: false, 
  Bananas: true, 
  Oranges: true
}
*/

按键排序的对象数组

let fruits = [
  {
    Bananas: true
  },
  {
    Apples: false
  },
  {
    oranges: true
  }
];

这可能是其中最棘手的,但上面应该有足够的信息来解决它。搞定它。

实时代码

查看 Chris Coyier 在 CodePen 上的笔 数组的字母排序 (@chriscoyier)。