Arranging in alphabetical order using JavaScript

I am trying to figure out how to sort my list of usernames in alphabetical order. Here is the code I have been working on, but it doesn't seem to be functioning properly. I have made some edits to the code.

script.js:

function displayUsers() {
  $("#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("<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a1c2cdc0c8d3c48fd1c0c6cfc8c4dbe1c2d4c3c3c4d38fc2cecc">[email protected]</a>: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 allData = data.users[i];
        console.log(allData);

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

                }
            },
  });
}

https://i.sstatic.net/FvLDb.png

Answer №1

If you're looking to arrange a string in alphabetical order, consider sorting the data.users array instead of looping through it. By utilizing the sort method along with String.prototype.localCompare, you can easily achieve your goal:

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

           // The 'users' array is now sorted alphabetically
        }

Answer №2

How can I arrange my list of usernames in alphabetical order?

If you have an array called data.users containing the usernames, you can easily sort them by name using the following code:

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

After sorting, you can then render the sorted usernames like this:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The Simple HTML Dom parser is failing to parse contents on these specific websites

I tried using a basic HTML DOM parser but it's encountering issues when parsing certain websites. include_once 'simple_html_dom.php'; $html=file_get_html('http://www.lapenderiedechloe.com/'); This results in an error message like ...

Contrast and remove the elements within jQuery array objects

As part of my data collection process, I am creating arrays to store lists of users for each request. Here is the code snippet that shows how I populate these arrays: $.each(data, function (i, item) { jQuery.each(array, function (index, data) { ...

What is the method for initiating a POST request in Java Script without including any data?

Currently, I am utilizing Ajax to send an array to the router, as demonstrated below... var send = function () { var data = search console.log(data) $.ajax({ type: 'post', url: ...

Using VueJS to fetch and display data from a JSON file using

Currently, I am dealing with a JSON value in the following format: { "T1" : "online", "T2" : "offline" } Additionally, I have an online API which only sends me the following response: { StatusCode :"T1" } My task is to extract the code from the API res ...

Vue.js - The $parent property is not accessible when a child component is nested within a <transition> element

Request: I need help with a situation involving two components, the parent component (Wall.vue) and the child component (PostItem.vue). Each PostItem includes a delete button. Upon clicking this button, a request is sent to the API to delete the item from ...

I'm having trouble getting my blockquote to work properly. Despite linking the bootstrap CSS and JS files, it still doesn't seem to be functioning

I have connected the downloaded css and js files from bootstrap, but the features are not working as expected. The <blockquote> tag is displaying only plain text, and the <cite></cite> element is not showing "-". What could be the reason ...

Querying Denormalized Data in AngularFire 0.82: Best Practices and Strategies

I have a question that is related to querying denormalized data with AngularFire. I am looking for a solution specifically using AngularFire (current version 0.82). Here is an example of the data structure I am working with: { "users": { "user1": { ...

AngularJS encountered an error: [$injector:modulerr] problem occurred during code execution

Hey there! I've been trying to set up a pop-up feature in Angular, but unfortunately, I keep encountering an error: Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.4.9/$injector/modulerr?p0=PopupDemo&p1=Error%…ogleapis.com%2Fa ...

Opera's compatibility with jQuery's Append method allows developers to

I recently wrote a jQuery script that interacts with a JSON feed and dynamically creates HTML code which is then added to a designated div on my WordPress site. Surprisingly, the functionality works flawlessly in all browsers except for Opera - where not ...

What is the best way to showcase Json API content on an HTML page?

I possess a strong proficiency in html and css, however I lack experience in utilizing javascript. My aim is to showcase the date received from an API onto an html page Despite several attempts, I have not been able to achieve success yet. var getJSON ...

What are the steps to utilizing dynamic data from a file in JavaScript?

I've got a Python script constantly generating data, and I'm looking to use that data to make some changes to an object in JavaScript. Is there a method to accomplish this? ...

Error in PromisifyAll: Callback parameter must be a function

Either my understanding of how BlueBird and its promisify function works is incorrect, or I am making a mistake in the following code. I have an "upload-handler" module that exports one function with a callback: The structure of the upload-handler functio ...

The indicated processing instruction is incompatible with the provided payment source. PayPal's hosted fields for credit card payments do not support this specific processor

I'm currently working on integrating credit card payments with hosted fields into my checkout process. However, I keep encountering an UNPROCESSABLE_ENTITY error when making the confirm-payment-source request through the PayPal JS SDK. Here is the co ...

Having trouble bringing my custom-built Angular module into my Angular application

Currently considering the utilization of this Yeoman generator as a starting point for a small project that will contain several reusable form components to be published. The generator constructs a module and an example component, directive, pipe, and serv ...

The issue with properly filtering a nested JSON object within an array in JavaScript

I am currently working on integrating a search input filter inside a dropdown menu that contains nested dropdown list items. The JSON data I receive from the API response is as follows: API response glPlmAsmt.category = { "page_size": 100, ...

What is the best way to send form values to the server using Ajax and Jquery?

Is there a smart way to utilize Ajax and jQuery for sending all input values from a dynamically generated form to the server? Manually listing each input name in the Ajax post seems cumbersome, so I'm wondering if there's a more elegant solution? ...

Incorporating JSON Objects within AngularJS

Currently, I am using AngularJS to fetch JSON data like this: $http.get('/balance').then(function (response) { $scope.balance = response.data; }); The value of response.data is as follows: { "pending": [{ "amount": 16, "currency": ...

Restricted scope / Effective method for passing an array to the directive user

Picture this scenario where a custom directive is referenced in myHtml.tpl.html: <my-directive></my-directive> This directive starts with an isolated scope. Naturally, there's a controller tied to myHtml.tpl.html. I aim to pass a compu ...

What is the best way to display a form within every row of a data table?

I am currently working on a page that retrieves data from a backend and displays it in a Datatable. One of the columns in my table is an input field with a default value fetched from the backend, and another column contains buttons. How can I implement a f ...

Duplicate messages are appearing at the message receiver front-end in the speedy chat due to Ajax polling

After developing a unique javascript chat system with php on the backend, the following techniques were utilized: 1) Implementing long-polling to retrieve new messages for the receiver 2) Utilizing sessionStorage to maintain the message counter 3) Utili ...