jQuery: removing duplicates from a list

Removing duplicated content from a list is quite a complex task if we don't know that all jQuery's methods for working with arrays simply deal with DOM nodes and not with their content. For that reason, we have to create an helper method to allow us to remove duplicated items from an an array. Let's see the details.

We have a list with some duplicated items:

<ul id="test">
  <li>Apple</li>
  <li>Banana</li>
  <li>Pear</li>
  <li>Orange</li>
  <li>Apple</li>
  <li>Banana</li>
  <li>Grapes</li>
  <li>Apple</li>
</ul>

We want to remove these items. First of all, we create an helper method to perform this task:

Array.prototype.removeDuplicates = function() {

  var temp = new Array();
  var i, len = this.length;
  
  this.sort();
  
  for(i = 0; i < len; i++) {
    
    if(this[i] == this[i+1]) {
    
      continue;
    
    
    }
    
    temp[temp.length] = this[i];
  
  }
  
  return temp;
} 

This method simply stores all the unique values in a new array. Now we can use jQuery:

$(function() {

  var items = [];
  
  $('li', '#test').each(function(i) {
  
    var text = $(this).text();
    items[i] = text;
  
  
  });
  
  var filteredItems = items.removeDuplicates();
  var html = '', i, len = filteredItems.length;
  
  for(i = 0; i < len; i += 1) {
  
    html += '<li>' + filteredItems[i] + '</li>';
  
  
  }
  
  $('#test').html(html);
  
    
});

We create a new array made of all of the text contents of our items, then we remove the duplicated contents and we use the filtered array to create a new DOM structure, which is as follows:

<ul id="test">
  <li>Apple</li>
  <li>Banana</li>
  <li>Grapes</li>
  <li>Orange</li>
  <li>Pear</li>
</ul>

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.