1

I've got a ul of various items which can have one of several possible data-attribute values, like this:

<ul>
    <li id="li1" data-cat="one">test item
    <li id="li2" data-cat="one">test no 2
    <li id="li3" data-cat="two">test dummy
    <li id="li4" data-cat="three">test no 4
    <li id="li5" data-cat="three">more test
    <li id="li6" data-cat="three">test no 6
</ul>

I'm attempting to use jQuery to select the first item of each distinct data-cat value - so for this example, li#li1, li#li3, and li#li4. I've tried building an array of each element with the data-attribute, then sorting with .unique like this

var list = $( '[data-cat]' ).get();
listSorted = jQuery.unique( list );
$( listSorted ).addClass('active');

But the code just selected all elements (see fiddle here)

I've found answers on SO like this one that come close, but they all seem to rely on knowing the data-attribute value beforehand and searching for that specific value. Is it possible to select the first element with a particular data-cat value without specifying the values beforehand?

1 Answer 1

6
var cats = {};
var list = $( '[data-cat]' ).filter(function(){
    var category = $(this).data("cat");

    if(cats[category]){
        // category already accounted for, return false
        return false;   
    } else {
        // first of this category
        cats[category] = true;
        return true;
    }
});

http://jsfiddle.net/nB3ru/5/

Sign up to request clarification or add additional context in comments.

3 Comments

Mines well just chain the addClass to the filter -> either way, +1
@tymeJV I did in the fiddle, just separated out the filter in the answer as I wasn't sure the addClass was really the endgoal.
@JamesMontagne way to make me feel like an idiot; this is great and looks much different than my poor attempts at solving the problem! You're right, the addClass wasn't really the objective, I just had it there to help me see what was being selected.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.