Katie Mellencomb
Katie Mellencomb

Reputation: 103

unique attribute values with jquery

is there a way to get all the unique values for a certain attribute.

e.g

<div class="bob" data-xyz="fish"></div>
<div class="bob" data-xyz="dog"></div>
<div class="bob" data-xyz="fish"></div>
<div class="bob" data-xyz="cat"></div>
<div class="bob" data-xyz="fish"></div>

I need to get all the distinct values for data-xyz attribute on div.bob,

so it should return fish, dog and cat.

Upvotes: 9

Views: 9741

Answers (3)

GolezTrol
GolezTrol

Reputation: 116110

Small code: Create an object and make 'dog' 'fish' 'cat' properties. That will make them unique. Then get the unique property names from the object. Simple and easy:

var items = {};
document.querySelectorAll('div.bob').forEach(function(element) {
    items[element.dataset['xyz']] = true; 
});

var result = new Array();
for(var i in items)
{
    result.push(i);
}
alert(result);

Note, the original answer from 2011 and the Fiddle used jQuery to find and iterate the elements and to read the data attribute, but it's just as easy using JavaScript as shown above.

Old loop:

$('div.bob').each(function() {
    items[$(this).attr('data-xyz')] = true; 
});

http://jsfiddle.net/GxxLj/1/

Upvotes: 10

Felix Kling
Felix Kling

Reputation: 816492

Keep track of which values you have already processed:

var seen = {};

var values = $('div.bob').map(function() {
    var value = this.getAttribute('data-xyz');
    // or $(this).attr('data-xyz');
    // or $(this).data('xyz');

    if(seen.hasOwnProperty(value)) return null;

    seen[value] = true;
    return value;
}).get();

Reference: $.map()

This, of course, only works with primitive values. In case you are mapping to objects, you'd have to override the toString() method of the objects so that they can be used as keys.

Or as plugin:

(function($) {

    $.fn.map_unique = function(callback) {
        var seen = {};
        function cb() {
            var value = callback.apply(this, arguments);
            if(value === null || seen.hasOwnProperty(value)) {
                return null;
            }
            seen[value] = true;
            return value;
        }
        return this.map(cb);
    });

}(jQuery));

Upvotes: 3

Dogbert
Dogbert

Reputation: 222198

var array = $('div.bob').map(function() { return $(this).data('xyz'); });

That will return all values. Then you can run it through a unique function.

How do I make an array with unique elements (i.e. remove duplicates)?

function ArrNoDupe(a) {
    var temp = {};
    for (var i = 0; i < a.length; i++)
        temp[a[i]] = true;
    var r = [];
    for (var k in temp)
        r.push(k);
    return r;
}
array = ArrNoDupe(array);

Upvotes: 2

Related Questions