Let’s say, we have an array of literals that contains some duplicate values −
const arr = ['Cat', 'Dog', 'Cat', 'Elephant', 'Dog', 'Grapes', 'Dog', 'Lion', 'Grapes', 'Lion'];
We are required to write a function that returns the count of unique elements in the array. Will use Array.prototype.reduce() and Array.prototype.lastIndexOf() to do this −
Example
const arr = ['Cat', 'Dog', 'Cat', 'Elephant', 'Dog', 'Grapes', 'Dog',
'Lion', 'Grapes', 'Lion'];
const countUnique = arr => {
return arr.reduce((acc, val, ind, array) => {
if(array.lastIndexOf(val) === ind){
return ++acc;
};
return acc;
}, 0);
};
console.log(countUnique(arr));Output
The output in the console will be −
5