Count unique elements in array without sorting JavaScript


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

Updated on: 26-Aug-2020

237 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements