简体   繁体   中英

Sort by alphabetical order in javascript

i would like to know how can i sort by alphabetical order my list of username here is my code but it's not working. I re)edit my code

script.js:

function displayuser() {
  $("#mySecond").empty();
    var x = document.getElementById("mySelect").value;

  $.ajax({
      url: "https://cubber.zendesk.com/api/v2/organizations/"+x+"/users.json",
      type: 'GET',
      dataType: 'json',
      cors: true ,
            contentType:'application/json',
            secure: true,
            beforeSend: function (xhr) {
                xhr.setRequestHeader ("Authorization", "Basic " + btoa("claire.pagniez@cubber.com:CC..11cc"));
            },
            success: function (data){
                for (i = 0; i < data.users.length; i++) {

          var username = data.users;
                          data.users.sort(function (a, b) {
                         return a.name.localeCompare(b.name);
                     });

                var userid = data.users[i].id;
        var all = data.users[i];
        console.log(all);

            $("#mySecond").append('<option value="'+ userid +'">'+ username +'</option>')

                }
            },
  });
}

在此处输入图片说明

You are trying to sort a string, you actually want to sort data.users , so you don't need to loop. Using sort combined with String.prototype.localCompare you can achieve what you want:

        success: function (data){
            var users = data.users;
            users.sort(function (a, b) {
                return a.name.localeCompare(b.name);
            });

           // users is now sorted
        }

how can i sort by alphabetical order my list of username

Assuming this is the username array data.users , you can sort it by name

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

and then render them

 for (i = 0; i < data.users.length; i++) 
 {
     var user = data.users[i];
     $("#mySecond").append('<option value="'+ user.id +'">'+ user .name +'</option>')
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM