
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
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 Articles
- Counting below / par elements from an array - JavaScript
- Unique number of occurrences of elements in an array in JavaScript
- Count unique elements in array without sorting JavaScript
- Counting possible APs within an array in JavaScript
- JavaScript program for counting frequencies of array elements
- Counting number of triangle sides in an array in JavaScript
- Finding unique string in an array in JavaScript
- Counting elements of an array using a recursive function in JS?
- Counting frequencies of array elements in C++
- Counting the occurrences of JavaScript array elements and put in a new 2d array
- 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?
- How do I make an array with unique elements (remove duplicates) - JavaScript?
- Counting n digit Numbers with all unique digits in JavaScript
- C program to find the unique elements in an array.

Advertisements