Sort array by firstname (alphabetically) in Javascript

前端 未结 23 2637
天命终不由人
天命终不由人 2020-11-22 11:46

I got an array (see below for one object in the array) that I need to sort by firstname using JavaScript. How can I do it?

var user = {
   bio: null,
   emai         


        
相关标签:
23条回答
  • 2020-11-22 12:17

    Pushed the top answers into a prototype to sort by key.

    Array.prototype.alphaSortByKey= function (key) {
        this.sort(function (a, b) {
            if (a[key] < b[key])
                return -1;
            if (a[key] > b[key])
                return 1;
            return 0;
        });
        return this;
    };
    
    0 讨论(0)
  • 2020-11-22 12:17

    You can use something similar, to get rid of case sensitive

    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;
    
    })
    
    0 讨论(0)
  • 2020-11-22 12:18

    Inspired from this answer,

    users.sort((a,b) => (a.firstname  - b.firstname));
    
    0 讨论(0)
  • 2020-11-22 12:19

    Shortest possible code with ES6!

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

    String.prototype.localeCompare() basic support is universal!

    0 讨论(0)
  • 2020-11-22 12:22

    Basically you can sort arrays with method sort, but if you want to sort objects then you have to pass function to sort method of array, so I will give you an example using your array

    user = [{
    bio: "<null>",
    email: "user@domain.com",
    firstname: 'Anna',
    id: 318,
    "last_avatar": "<null>",
    "last_message": "<null>",
    lastname: 'Nickson',
    nickname: 'anny'
    },
    {
    bio: "<null>",
    email: "user@domain.com",
    firstname: 'Senad',
    id: 318,
    "last_avatar": "<null>",
    "last_message": "<null>",
    lastname: 'Nickson',
    nickname: 'anny'
    },
    {
    bio: "<null>",
    email: "user@domain.com",
    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;
    });
    
    0 讨论(0)
  • 2020-11-22 12:23

    My implementation, works great in older ES versions:

    sortObject = function(data) {
        var keys = Object.keys(data);
        var result = {};
    
        keys.sort();
    
        for(var i = 0; i < keys.length; i++) {
            var key = keys[i];
    
            result[key] = data[key];
        }
    
        return result;
    };
    
    0 讨论(0)
提交回复
热议问题