Remove Duplicates from Dropdown List By javascript only
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
Why don't you get get items uniquely from database?
– Mojtaba Ahmadi
Sep 7 '18 at 7:22
2 Answers
2
Javascript has removeChild
option, you can use it to remove duplicate value:
removeChild
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>
stackoverflow.com/questions/17708014/…
– manikant gautam
Sep 7 '18 at 7:26
Another option is to use the set as suggested here: alternatives or another alternative.
[ ...new Set([ ...<arg1>, ...<arg2> ]) ]
for e.g.
[ ...new Set([ ...<arg1>, ...<arg2> ]) ]
var y = [ ...new Set([ ...[1, 2, 3, 4, 5], ...[3, 4, 5] ]) ]
var y = [ ...new Set([ ...[1, 2, 3, 4, 5], ...[3, 4, 5] ]) ]
// expected output: [ 1, 2, 3, 4, 5 ]
// expected output: [ 1, 2, 3, 4, 5 ]
Use the output to bind to the dropdown list.
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
How are you creating that list?
– ritaj
Sep 7 '18 at 7:17