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.
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.
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.
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