Sometimes, no matter how much you’d like to, you aren’t able to control the direct output of code without spinning up an entire custom solution devoted to eliminating the issue. For the short term though, there’s jQuery to the rescue.

By utilizing jQuery, we’re able to alter the output after the fact, which means we can achieve more desirable results—in this case, pare down a list and remove the duplicates—fairly quickly.

// Get the list of all names and drop them in an array
var names = [];
$('.container ul li').each( function() {
    names.push($(this).text().toLowerCase());
});

// Destroy the original list since we don't want it with duplicates
$('.container ul').remove();

// Now let's remove the duplicates...
var uniqueNames = [];
$.each( names, function(i, el) {
    if($.inArray(el, uniqueNames) === -1) {
        uniqueNames.push(el);
    }   
});

var newList = $(''); // New UL
outputList(uniqueNames); // Run function and fill the UL with unique names
newList.appendTo($('.container')); // Append the completed UL to original DIV

// Create a list item for each item and append to new UL
function outputList(result) {
    $.each( result, function(index, value) {
        $('
').text(value).appendTo(newList);
    });
}

Original Stackoverflow Reference: http://stackoverflow.com/questions/9229645/remove-duplicates-from-javascript-array

Leave a Reply

Your email address will not be published. Required fields are marked *

Continue Reading