Sort array by firstname (alphabetically) in Javascript

前端 未结 23 2678
天命终不由人
天命终不由人 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: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: "",
    email: "user@domain.com",
    firstname: 'Anna',
    id: 318,
    "last_avatar": "",
    "last_message": "",
    lastname: 'Nickson',
    nickname: 'anny'
    },
    {
    bio: "",
    email: "user@domain.com",
    firstname: 'Senad',
    id: 318,
    "last_avatar": "",
    "last_message": "",
    lastname: 'Nickson',
    nickname: 'anny'
    },
    {
    bio: "",
    email: "user@domain.com",
    firstname: 'Muhamed',
    id: 318,
    "last_avatar": "",
    "last_message": "",
    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;
    });
    

提交回复
热议问题