Counting unique elements in an array in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that counts all unique items in an array. The function should return an object representing the count of each unique element of the array.

Therefore, let’s write the code for this function −

Example

The code for this will be −

const arr = ["hi", "hello", "hi"];
const countUnique = arr => {
   const counts = {};
   for (var i = 0; i < arr.length; i++) {
      counts[arr[i]] = 1 + (counts[arr[i]] || 0);
   };
   return counts;
};
console.log(countUnique(arr));

Output

The output in the console will be −

{ hi: 2, hello: 1 }
raja
Published on 24-Oct-2020 15:22:00
Advertisements