Search code examples
jqueryjquery-selectorseachno-duplicatesjquery-filter

jQuery selector to get just the first occurrence of every value


I have an HTML like this:

<div data-value="a"></div>
<div data-value="b"></div>
<div data-value="c"></div>
<div data-value="d"></div>
<div data-value="a"></div>
<div data-value="d"></div>
<div data-value="e"></div>

I would like to use jQuery to select all the divs with a different data-value attribute.

Here's my attempt:

$( document ).ready(function() {
    $('div[data-value]').each(function(){
        var value = $(this).data("value");
        console.log(value);
    });
});

This of course will print out all the occurrences: a, b, c, d, a, d, e.

Instead I need to print just the first occurrence of every value: a, b, c, d, e.

Yes, I could use an array to put elements in it and check if it's already in there and do my stuff, but I'm looking for a compact and elegant jQuery code, like a selector or a filter function or something. Any idea?

Fiddle


Solution

  • I would like to select with jquery all the div with different data-value attribute.
    ....
    like a selector or a filter function or something
    ....

    I'm assuming the others didn't read the question, and that you really wanted to select the elements that had unique data attributes, not just get an array with the values of those attributes.

    A filter seems like the correct approach here, checking if the currently iterated element is the first one with that data-value etc

    $('div[data-value]').filter(function(_, x) {
        return $('div[data-value="' + $(x).data('value') + '"]').get(0) === this;
    });
    

    FIDDLE