Count unique elements in array without sorting JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

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
raja
Published on 26-Aug-2020 11:36:52
Advertisements