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






How are you creating that list?

– ritaj
Sep 7 '18 at 7:17






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.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)