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

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

当前回答

你可以使用类似的方法来消除区分大小写的问题

users.sort(function(a, b){

  //compare two values
  if(a.firstname.toLowerCase() < b.firstname.toLowerCase()) return -1;
  if(a.firstname.toLowerCase() > b.firstname.toLowerCase()) return 1;
  return 0;

})

其他回答

简单地说,你可以使用这种方法

users.sort(function(a,b){return a.firstname < b.firstname ? -1 : 1});

您可以将此用于对象

transform(array: any[], field: string): any[] {
return array.sort((a, b) => a[field].toLowerCase() !== b[field].toLowerCase() ? a[field].toLowerCase() < b[field].toLowerCase() ? -1 : 1 : 0);}

你可以使用类似的方法来消除区分大小写的问题

users.sort(function(a, b){

  //compare two values
  if(a.firstname.toLowerCase() < b.firstname.toLowerCase()) return -1;
  if(a.firstname.toLowerCase() > b.firstname.toLowerCase()) return 1;
  return 0;

})

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

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

使用ES6的最短代码!

users.sort((a, b) => a.firstname.localeCompare(b.firstname))

String.prototype.localeCompare()基本支持是通用的!