Abhinav Parashar
Abhinav Parashar

Reputation: 649

Remove Duplicates from Dropdown List By javascript only

I have a select dropdown field that is being created dynamically from a database . Due to the way this is being created it results in the dropdown having duplicate items and values.

<select id="locationList">
<option value="1">Andover</option>
<option value="2">Bishops waltham</option>
<option value="1">Andover</option>
<option value="3">Boscombe</option>
<option value="4">Bournemouth</option>
<option value="2">Bishops waltham</option>
<option value="4">Bournemouth</option>

</select>

Does anyone know if there is a way to use some code on the page which checks the dropdown for duplicates and removes duplicates from the menu only by Javascript No Jquery?

Thanks in advance,

Abhinav

Upvotes: 0

Views: 2636

Answers (3)

Lakhvir Singh
Lakhvir Singh

Reputation: 102

Do it with dual for loop using pure js

Simple and easy way with select remove method

function clearList() {
  var x = document.getElementById("locationList");
  //count the lenth of select optons
  var listLength = x.length;
  for (var i = 0; i < listLength; i++) {
    for (var j = 0; j < listLength; j++) {
      //i != j This prevents the actual index from being deleted
      //x.options[i].value == x.options[j].value => it finds the duplicate index.
      if (x.options[i].value == x.options[j].value && i != j) {
        //Remove duplicate option element
        x.remove(j);
        //Refresh the list Length
        listLength--;
      }
    }
  }
}
<select id="locationList">
  <option value="1">Andover</option>
  <option value="2">Bishops waltham</option>
  <option value="1">Andover</option>
  <option value="3">Boscombe</option>
  <option value="4">Bournemouth</option>
  <option value="2">Bishops waltham</option>
  <option value="4">Bournemouth</option>
</select>

<p>Click to remove duplicates</p>
<button onclick="clearList()">Remove</button>

Upvotes: 0

Koshux
Koshux

Reputation: 346

Another option is to use the set as suggested here: alternatives or another alternative.

[ ...new Set([ ...<arg1>, ...<arg2> ]) ] for e.g.

var y = [ ...new Set([ ...[1, 2, 3, 4, 5], ...[3, 4, 5] ]) ]

// expected output: [ 1, 2, 3, 4, 5 ]

Use the output to bind to the dropdown list.

Upvotes: 0

saAction
saAction

Reputation: 2065

Javascript has removeChild option, you can use it to remove duplicate value:

var fruits = document.getElementById("locationList");

[].slice.call(fruits.options)
  .map(function(a){
    if(this[a.value]){ 
      fruits.removeChild(a); 
    } else { 
      this[a.value]=1; 
    } 
  },{});
<select id="locationList">
<option value="1">Andover</option>
<option value="2">Bishops waltham</option>
<option value="1">Andover</option>
<option value="3">Boscombe</option>
<option value="4">Bournemouth</option>
<option value="2">Bishops waltham</option>
<option value="4">Bournemouth</option>
</select>

Upvotes: 1

Related Questions