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.

Junaid afzal
  • 109
  • 5
  • 17
  • 2
    You should avoid duplicates server side – A. Wolff Jan 15 '16 at 11:16
  • But if you want to do it with js yes or yes, check this: http://stackoverflow.com/a/9229821/3648578 – kosmos Jan 15 '16 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. – Junaid afzal Jan 15 '16 at 11:18
  • @kosmos How I achieve this in my scenario. can you please edit my code. Thanks. – Junaid afzal Jan 15 '16 at 11:24
  • 1
    With PHP, you can store all countries in an array, then clean your array with [`array_unique()`](http://php.net/manual/es/function.array-unique.php) method and then make a `foreach()` with that result to paint the countries without duplicates. – Marcos Pérez Gude Jan 15 '16 at 11:24
  • @MarcosPérezGude I have no countries in PHP array. I am listing countries in simple HTML. I am fetching the already stored countries in database and showing in Select option list. But now I am getting the duplicate values. How I remove? Thanks. – Junaid afzal Jan 15 '16 at 11:31
  • I don't know why don't you fetch the countries directly from database, but with javascript is the same procedure: store all countries in an array, remove duplicates (see the function [`array_unique()`](http://phpjs.org/functions/array_unique/) from phpjs.org) and then paint all without duplicates. If this method is valid for you, I can make a complete answer with that. – Marcos Pérez Gude Jan 15 '16 at 11:37
  • Here you are a javascript solution. Good luck! – Marcos Pérez Gude Jan 15 '16 at 11:55
  • @Junaidafzal can you tell me if it fits with your requirements? – Marcos Pérez Gude Jan 15 '16 at 12:17
  • @MarcosPérezGude Thanks for your code. but it's not working. should I also need to include phpjs library into my file? – Junaid afzal Jan 15 '16 at 12:29
  • @MarcosPérezGude When I alert the cleanedArray. It gives the following output.. [object Object]..?? – Junaid afzal Jan 15 '16 at 12:35
  • Logical. In javascript, all is an object, an array is an object too. – Marcos Pérez Gude Jan 15 '16 at 12:39
  • yes it is showing on console but why i am still getting the duplicate values in my Select option list?? Thanks for your reply – Junaid afzal Jan 15 '16 at 12:43

2 Answers2

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.

Community
  • 1
  • 1
Roamer-1888
  • 19,138
  • 5
  • 33
  • 44
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>
Marcos Pérez Gude
  • 21,869
  • 4
  • 38
  • 69
  • When I alert the cleanedArray. It gives the following output.. [object Object]..?? – Junaid afzal Jan 15 '16 at 12:35
  • 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 – Marcos Pérez Gude Jan 15 '16 at 12:38
  • yes it is showing on console but why i am still getting the duplicate values in my Select option list?? Thanks for your reply. – Junaid afzal Jan 15 '16 at 12:42
  • Did you notice this line? `$(this).remove(); // remove the option element` – Marcos Pérez Gude Jan 15 '16 at 12:48
  • Yes I notice that line but can't understand. can you please tell me where the problem is. thanks for your help. – Junaid afzal Jan 15 '16 at 12:51
  • I edit the answer and put a snippet with the working example. Note that `Algeria` is 3 times, but when you run the snippet the duplicates are removed. So the code works perfectly. If you can't make work this code, please, add your code with your problem in a snippet (or a jsfiddle.org if it's better for you) – Marcos Pérez Gude Jan 15 '16 at 12:53
  • The code is commented. First read all options (with duplicates) and store in an array (this code is yours), but I add the deletion of the options to make empty the entire ` – Marcos Pérez Gude Jan 15 '16 at 12:55