我得到了一个数组(见下面数组中的一个对象),我需要使用JavaScript按名字排序。 我该怎么做呢?

var user = {
   bio: null,
   email:  "user@domain.example",
   firstname: "Anna",
   id: 318,
   lastAvatar: null,
   lastMessage: null,
   lastname: "Nickson",
   nickname: "anny"
};

当前回答

一个广义函数可以这样写

    function getSortedData(data, prop, isAsc) {
        return data.sort((a, b) => (a[prop] < b[prop] ? -1 : 1) * (isAsc ? 1 : -1));
   }

您可以传递以下参数

要排序的数据 数据中的属性应该按它排序 最后一个参数为布尔类型。它检查你是要升序排序还是降序排序

其他回答

我很惊讶居然没人提到Collators。除非迫不得已,否则不应该使用localeCompare,因为它的性能明显较差

const collator = new Intl.Collator('zh-CN'); // Chinese Simplified for example

function sortAsc(a, b) {
  if (typeof a === 'string' && typeof b === 'string') {
    return collator.compare(b, a)
  }

  return b - a;
}

function sortDesc(a, b) {
  if (typeof a === 'string' && typeof b === 'string') {
    return collator.compare(a, b);
  }

  return a - b;
}

同样,对于asec和desc排序,你可以使用这个: 假设我们有一个变量SortType,指定你想要的升序排序或降序排序:

 users.sort(function(a,b){
            return   sortType==="asc"? a.firstName.localeCompare( b.firstName): -( a.firstName.localeCompare(  b.firstName));
        })

如果比较的字符串包含unicode字符,您可以使用String类的localeCompare函数,如下所示:

users.sort(function(a,b){
    return a.firstname.localeCompare(b.firstname);
})

漂亮的小ES6内衬:

users.sort((a, b) => a.firstname !== b.firstname ? a.firstname < b.firstname ? -1 : 1 : 0);

基本上你可以用sort方法对数组排序,但如果你想对对象排序,你就必须传递function给数组的sort方法,我会给你一个使用数组的例子

user = [
  {
    bio: "<null>",
    email: "user@domain.example",
    firstname: "Anna",
    id: 318,
    last_avatar: "<null>",
    last_message: "<null>",
    lastname: "Nickson",
    nickname: "anny",
  },
  {
    bio: "<null>",
    email: "user@domain.example",
    firstname: "Senad",
    id: 318,
    last_avatar: "<null>",
    last_message: "<null>",
    lastname: "Nickson",
    nickname: "anny",
  },
  {
    bio: "<null>",
    email: "user@domain.example",
    firstname: "Muhamed",
    id: 318,
    last_avatar: "<null>",
    last_message: "<null>",
    lastname: "Nickson",
    nickname: "anny",
  },
];

var ar = user.sort(function (a, b) {
  var nA = a.firstname.toLowerCase();
  var nB = b.firstname.toLowerCase();

  if (nA < nB) return -1;
  else if (nA > nB) return 1;
  return 0;
});