

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Counting unique elements in an array in JavaScript
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 }
- Related Questions & Answers
- Counting below / par elements from an array - JavaScript
- Unique number of occurrences of elements in an array in JavaScript
- Counting possible APs within an array in JavaScript
- Count unique elements in array without sorting JavaScript
- Counting frequencies of array elements in C++
- Finding unique string in an array in JavaScript
- Counting elements of an array using a recursive function in JS?
- Counting number of triangle sides in an array in JavaScript
- How do I make an array with unique elements (remove duplicates) - JavaScript?
- C program to find the unique elements in an array.
- Counting n digit Numbers with all unique digits in JavaScript
- Sorting array of exactly three unique repeating elements in JavaScript
- JavaScript Count the number of unique elements in an array of objects by an object property?
- Extract unique values from an array - JavaScript
- Counting the occurrences of JavaScript array elements and put in a new 2d array
Advertisements