Jim Miller
Jim Miller

Reputation: 3329

Can you find the number of different values of an attribute w. jQuery?

Suppose I have a structure like so:

<div class='collection'>
    <div class='item' seq=1>foo</div>
    <div class='item' seq=2>bar</div>
    <div class='item' seq=2>baz</div>
    <div class='item' seq=2>asd</div>
    <div class='item' seq=3>que</div>
    <div class='item' seq=3>bletch</div>
</div>

It's easy to get the number of items with seq=1, seq=2, etc. But how would you find the number of different values of seq, and what those values are? It's probably safe to assume that the values of seq will start at 1 and go up by 1 until there are no more.

Upvotes: 1

Views: 56

Answers (2)

Darren
Darren

Reputation: 70728

You could do something like:

var items = [];
$(".collection > .item").each(function() {
   var sequence = $(this).attr("seq");
    if (jQuery.inArray(sequence, items) == -1) {
         items.push(sequence);
    }
});

This would declare an array called items and loop round each div. If the sequence is not in the array it adds the sequence value.

Upvotes: 1

Fr&#233;d&#233;ric Hamidi
Fr&#233;d&#233;ric Hamidi

Reputation: 262919

You can accumulate the attribute values and their count in an object:

var totals = {};
$(".collection > .item").each(function() {
    var seq = $(this).attr("seq");
    var total = totals[seq] || 0;
    totals[seq] = total + 1;
});

When the above code has run, you should have an object like:

{
    "1": 1,
    "2": 3,
    "3": 2
}

Upvotes: 5

Related Questions