-3

I need a JavaScript function which is capable of counting the number of unique items in an array (i.e. ignoring duplicates). For example,

var r = [car, car, bike, bike, truck]

The result should be 3 instead of 5.

user1033038
  • 141
  • 3
  • 15

3 Answers3

2

Try this:

var r = ['car', 'car', 'bike', 'bike', 'truck'];
var counts = [], count = 0, i = 0;
for(i=0; i<r.length; i++) {
    if(counts[r[i]] == undefined) {
        counts[r[i]] = 1;
        count++;
    }
}
console.log(count);

For a given array, this prints the number of unique elements in the array.

techfoobar
  • 63,712
  • 13
  • 108
  • 129
1
Array.prototype.count_unique = function() {
    var arr2 = [];
    for (i = this.length; i--;) {
        if (arr2.indexOf( this[i] ) == -1) arr2.push( this[i] );
    }
    return arr2.length;
}

used

var r      = ['car', 'car', 'bike', 'bike', 'truck'],
    unique = r.count_unique();

FIDDLE

adeneo
  • 303,455
  • 27
  • 380
  • 377
0

Use Array.filter()

var arr = ['car', 'car', 'bike', 'bike', 'truck'],
    countUniques = arr.filter(function(elem, index, self) {
    return index == self.indexOf(elem);
}).length;
alert(countUniques); //will show 3

If you want it to be appliable to all Arrays:

Array.prototype.countUniques = function() {
    return this.filter(function(elem, index, self) {
        return index == self.indexOf(elem);
    }).length;
};

Usage: arr.countUniques() // 3

Niccolò Campolungo
  • 11,350
  • 3
  • 32
  • 38