John Doe
John Doe

Reputation: 71

How to sort an array alphabetically in a dropdownlist

I'm trying to sort the next dropdownlist with the sort () function of fixes but it doesn't work for me

The following is the dropdownlist that I try to sort alphabetically with the javascript function that loads the data

function loadService() {
    const url = document.getElementById("service").value;
    $.ajax({
        url: url,
        type: "POST",
        dataType: "json",
        success: function(data) {
            if (data.length > 0) {
                const service = document.getElementById("ticketServiceInput");

                const arrDataSorted = data.sort((a, b) => (a.value > b.value) ? 1 : ((b.value > a.value) ? -1 : 0));

                for (let idx in arrDataSorted) {
                    if (arrDataSorted.hasOwnProperty(idx)) {
                        const option = document.createElement("option");
                        option.innerHTML = arrDataSorted[idx].Name;
                        option.value = arrDataSorted[idx].ServiceId;
                        service.options.add(option);                  
                    }
                }               
            }           
        }
    });
};
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

<div class="form-group" id="ServiceDiv">
                                    <label class="required-field" name="service" for="ticketServiceInput">Service:</label>
                                    <select id="ticketServiceInput" name="service" onchange="loadSubService(); validate(this)" class="form-control form-control-use validateable" style="width: 100%; padding: 0.375rem 0.75rem; height: 50px;" tabindex="-1" aria-hidden="true">
                                        <option value="" disabled selected>Select a option</option>
                                    </select>
                                  
                                </div>

I don't know if I'll be executing the sort function the wrong way or what might be happening

UPDATE:

Try the following but no result

function loadService() {
    const url = document.getElementById("service").value;
    $.ajax({
        url: url,
        type: "POST",
        dataType: "json",
        success: function(data) {
            if (data.length > 0) {
                const service = document.getElementById("ticketServiceInput");

                const arrDataSorted = data.sort((a, b) => {
                    return a.value - b.value;
                } );



                for (let idx in arrDataSorted) {
                    if (arrDataSorted.hasOwnProperty(idx)) {
                        const option = document.createElement("option");
                        option.innerHTML = arrDataSorted[idx].Name;
                        option.value = arrDataSorted[idx].ServiceId;
                        service.options.add(option);                  
                    }
                }               
            }           
        }
    });
};

Upvotes: 1

Views: 501

Answers (2)

Lee Salminen
Lee Salminen

Reputation: 880

Turns out the answer was to change

const arrDataSorted = data.sort((a, b) => (a.value > b.value) ? 1 : ((b.value > a.value) ? -1 : 0));

to

const arrDataSorted = data.sort((a, b) => (a.Name > b.Name) ? 1 : ((b.Name > a.Name) ? -1 : 0));

After Sebastian provided his example data of

[{"ServiceId":1,"Name":"BLACKBOARD","Content":"Software de educación"}...]

it became clear he wanted to sort on the Name property of the Object and not the value.

Chev in another answer recommended using lodash to help with these sorting functions, which I definitely agree with. Lodash is a great tool when working with JS.

Upvotes: 1

Samuel Goldenbaum
Samuel Goldenbaum

Reputation: 18909

Why not use lodash sortby for this. Nice and simple. Given the data you shared:

    arrDataSorted = _.sortBy(data, (x) => {
      return x.Name;
    });

Or use your function:

 let arrDataSorted = data.sort(function(a, b) {
        var nameA = a.Name.toUpperCase(); // ignore upper and lowercase
        var nameB = b.Name.toUpperCase(); // ignore upper and lowercase
        if (nameA < nameB) {
          return -1;
        }
        if (nameA > nameB) {
          return 1;
        }

        // names must be equal
        return 0;
    });

Upvotes: 1

Related Questions