Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unique attribute values with jquery

Tags:

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.

like image 732
Katie Mellencomb Avatar asked Sep 04 '11 09:09

Katie Mellencomb


3 Answers

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 = {};
$('div.bob').each(function() {
    items[$(this).attr('data-xyz')] = true; 
});

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

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

like image 127
GolezTrol Avatar answered Sep 29 '22 12:09

GolezTrol


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));
like image 24
Felix Kling Avatar answered Sep 29 '22 11:09

Felix Kling


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);
like image 20
Dogbert Avatar answered Sep 29 '22 11:09

Dogbert