StackOverflow StackOverflow - 3 months ago 12
jQuery Question

how to check for dupes & not display them

I want to check for duplicates in the list IDs in this function & not display them, All this is doing is adding the listIDs into the container but it is not checking for duplicates

var listIDs = [];
$.each(this.$el('lists', true), function(index, el) {
listIDs.push($(el).data('containerid'));
});


Any help would be greatful

Answer

To check whether an item already exists in an array, you can use indexOf.

var listIDs = [];
$.each(this.$el('lists', true), function(index, el) {
    var id = $(el).data('containerid')
    if (listIDs.indexOf(id) === -1) {
        listIDs.push(id)
    }
})

If id is not already in listIDs, then listIDs.indexOf(id) will return -1. In this case, we add it.