1

I am getting the duplicate values in my multiple select options list and values are coming dynamically from database in PHP. Now I want to remove those duplicate values from my multiple select options list. How I achieve this Javascript or Jquery? Below is my code.

HTML

<select name="countries[]" id="update_supp_last_countries" style="width:305px;" multiple="multiple" required>



<?php 
        foreach($supp_last_count_Row as $results5){
        $supp_last_country5[$i5] = $results5['countries'];
        $i5++;
         ?>

<option value='<?php echo $supp_last_country5[$itr5];?>' selected> <?php echo $supp_last_country5[$itr5];?> </option>
<?php $itr5++; } ?>

<option value="Afghanistan">Afghanistan</option>
<option value="Albania">Albania</option>
<option value="Algeria">Algeria</option>
<option value="American Samoa">American Samoa</option>
<option value="Andorra">Andorra</option>
<option value="Angola">Angola</option>
<option value="Anguilla">Anguilla</option>
<option value="Antartica">Antarctica</option>
<option value="Antigua and Barbuda">Antigua and Barbuda</option>

Javascript

var optionValues = [];
$('#update_supp_last_countries option').each(function() {
optionValues.push($(this).val());
});
var size = optionValues.length;
alert(optionValues);

Now I am getting the duplicated values in optionValues Array. How can I remove this. Thanks in advance.

13
  • 2
    You should avoid duplicates server side Commented Jan 15, 2016 at 11:16
  • But if you want to do it with js yes or yes, check this: stackoverflow.com/a/9229821/3648578 Commented Jan 15, 2016 at 11:17
  • @A.Wolff How should I remove can you please guide me. I am making the edit page where I want to show selected values which earlier stored in database. Thanks for your reply. Commented Jan 15, 2016 at 11:18
  • @kosmos How I achieve this in my scenario. can you please edit my code. Thanks. Commented Jan 15, 2016 at 11:24
  • 1
    With PHP, you can store all countries in an array, then clean your array with array_unique() method and then make a foreach() with that result to paint the countries without duplicates. Commented Jan 15, 2016 at 11:24

2 Answers 2

1

It would be good if jQuery.unique() did this kind of job, but it does something different and isn't suitable for adaptation.

Hmffff, if we want a jQuery method, we have to write our own plugin.

jQuery.fn.uniqueAttrs = function(attr) {
    if(!attr) return this;
    var that = this;
    return this.filter(function (index, node) {
        return that.index(that.filter(function() {
            return this[attr] === node[attr];
        })) === index;
    });
};

Call like this :

var $ul = $('#update_supp_last_countries');
$ul.html($ul.find('option').uniqueAttrs('value'));

DEMO

Explanation :

This answer provides a neat solution to filtering out duplicate values from a js array. Slight adaptation is necessary to make the same approach work on a jQuery collection, and to filter on a matching attribute ("value" in this case).

The good things about this approach are that :

  • it is dependent only on jQuery,
  • the option elements don't need to be rebuilt - a collection comprising filtered original elements is returned, with no assumptions about the nodes in the collection (other than that the given attribute exists). Therefore the plugin has a good measure of reusability.

If there's a downside, it's that a filter within a filter isn't highly desirable for performance. The plugin will be noticably slow with more than a few hundred elements. On my little 1.6 GHz machine (with performance issues) I got these figures, averaged over several runs :

  • 20 options: 40 ms
  • 50 options: 50 ms
  • 100 options: 75 ms
  • 200 options: 300 ms
  • 400 options: 600 ms

Also for some reason I don't understand, if $ul.html($ul.find('option').uniqueAttrs('value')) is repeatedly applied, then the selectedIndex advances by one element each time - DEMO.

Sign up to request clarification or add additional context in comments.

Comments

0

I use http://phpjs.org function (array_unique()) to delete duplicates, null, empty or false values from the array.

All I make is store all countries in an array, clean the array for duplicates or falsy values and then repaint it.

// array_unique compressed:
    function array_unique(d){var c="",b={},e="";var a=function(h,g){var f="";for(f in g){if(g.hasOwnProperty(f)){if((g[f]+"")===(h+"")){return f}}}return false};for(c in d){if(d.hasOwnProperty(c)){e=d[c];if(false===a(e,b)){b[c]=e}}}return b};


var optionValues = [];
$('#update_supp_last_countries option').each(function() {
  optionValues.push($(this).val());
  $(this).remove(); // remove the option element
});

var cleanedArray = array_unique(optionValues); // clean the array

// let's go to paint the new options
for(var i in cleanedArray) {
  var opt = $('<option/>')
                .attr('value', cleanedArray[i]) // note that the value is equal than the text
                .text(cleanedArray[i]);
  $('#update_supp_last_countries').append(opt);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="update_supp_last_countries">
  <option value="Afghanistan">Afghanistan</option>
  <option value="Albania">Albania</option>
  <option value="Algeria">Algeria</option>
  <option value="Algeria">Algeria</option>
  <option value="Algeria">Algeria</option>
  <option value="American Samoa">American Samoa</option>
  <option value="Andorra">Andorra</option>
  <option value="Angola">Angola</option>
  <option value="Anguilla">Anguilla</option>
  <option value="Angola">Angola</option>
  <option value="Anguilla">Anguilla</option>
  <option value="Angola">Angola</option>
  <option value="Anguilla">Anguilla</option>
  <option value="Angola">Angola</option>
  <option value="Anguilla">Anguilla</option>
  <option value="Angola">Angola</option>
  <option value="Anguilla">Anguilla</option>
  <option value="Antartica">Antarctica</option>
  <option value="Antigua and Barbuda">Antigua and Barbuda</option>
</select>

7 Comments

When I alert the cleanedArray. It gives the following output.. [object Object]..??
Obviously, cleanedArray is an array, and in javascript array is an object. So the alert throws that. Put console.log(cleanedArray) instead of alert(cleanedArray) and you can see all values in your console. This code works perfectly
yes it is showing on console but why i am still getting the duplicate values in my Select option list?? Thanks for your reply.
Did you notice this line? $(this).remove(); // remove the option element
Yes I notice that line but can't understand. can you please tell me where the problem is. thanks for your help.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.