Search code examples
javascriptarrayssortingdropdown

Sort API results alphabetically in dropdown element (Javascript Only Please)


I have two dropdown elements below that are populated with data from the result array.

I simply want to sort each option coming from the result array alphabetically in the drop-down elements.

Would also like to mention that in my dev environment the result data is actually coming from an API.

Thanks in advance!

let result = [{
    name: "B name",
    tag: "B tag",
    price: "50"
  },
  {
    name: "C name1",
    tag: "C tag",
    price: "10"
  },
  {
    name: "A name",
    tag: "A tag",
    price: "20"
  },
  {
    name: "E name",
    tag: "E tag",
    price: "30"
  },
  {
    name: "D name",
    tag: "D tag",
    price: "40"
  }
];

//Generic function to fill a dropdown with options 
let populateDropDown = (params) => {
  let set = new Set()
  params.optionsToPopulate.forEach(item => {
    const txt = item[params.text];
    if (!set.has(txt)) {
      params.element.add(new Option(txt, txt))
       set.add(txt);
    }
  })
}

//Initialize tags dropdown
(function() {
  document.getElementById("tags").addEventListener('change', (event) => {
    tagChanged(event);
  });

  let params = {
    optionsToPopulate: result,
    element: document.getElementById("tags"),
    id: "tag",
    text: "tag"
  }
  populateDropDown(params);

})();

//Tags dropdown change event.
let tagChanged = (event) => {
  let tagValue = event.target.value;

  //filter the results based on the value of tags dropdown
  let optionsToAdd = result.filter(item => item.tag === tagValue);
  let names = document.getElementById("names");
  names.options.length = 1;
  let params = {
    optionsToPopulate: optionsToAdd,
    element: names,
    id: "name",
    text: "name"
  }
  populateDropDown(params);
}
<!DOCTYPE html>
<html>

<head>
  <title></title>
</head>

<body>
  Tags:
  <select id="tags">
  <option value="please select">please select</option> 
  </select>

  <br><br><br> Names:
  <select id="names">
  <option value="please select">please select</option> 
  </select>

</body>

</html>


Solution

  • let result = [{
        name: "B name",
        tag: "B tag",
        price: "50"
    },
    {
        name: "C name1",
        tag: "C tag",
        price: "10"
    },
    {
        name: "A name",
        tag: "A tag",
        price: "20"
    },
    {
        name: "E name",
        tag: "E tag",
        price: "30"
    },
    {
        name: "D name",
        tag: "D tag",
        price: "40"
    }
    ];
    
    // Sort Alphabetically
    var sortedResult = result.sort(function (a, b) {
        var tagA = a.tag.toLowerCase();
        var tagB = b.tag.toLowerCase();
    
        if (tagA < tagB)
            return -1;
        else if (tagA > tagB)
            return 1;
    });
    
    //Generic function to fill a dropdown with options 
    let populateDropDown = (params) => {
        let set = new Set()
        params.optionsToPopulate.forEach(item => {
            const txt = item[params.text];
            if (!set.has(txt)) {
                params.element.add(new Option(txt, txt))
                set.add(txt);
            }
        })
    }
    
    //Initialize tags dropdown
    (function () {
        document.getElementById("tags").addEventListener('change', (event) => {
            tagChanged(event);
        });
    
        let params = {
            optionsToPopulate: sortedResult,
            element: document.getElementById("tags"),
            id: "tag",
            text: "tag"
        }
        populateDropDown(params);
    
    })();
    
    //Tags dropdown change event.
    let tagChanged = (event) => {
        let tagValue = event.target.value;
    
        //filter the results based on the value of tags dropdown
        let optionsToAdd = sortedResult.filter(item => item.tag === tagValue);
        let names = document.getElementById("names");
        names.options.length = 1;
        let params = {
            optionsToPopulate: optionsToAdd,
            element: names,
            id: "name",
            text: "name"
        }
        populateDropDown(params);
    }
    Tags:
    <select id="tags">
        <option value="please select">please select</option>
    </select>
    
    <br><br><br> Names:
    <select id="names">
        <option value="please select">please select</option>
    </select>