
- 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
JavaScript function that should count all unique items in an array
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.
Let’s say the following is our array −
const arr = ["hi", "hello", "hi"];
Example
Following is the code −
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
This will produce the following output on console −
{ hi: 2, hello: 1 }
- Related Articles
- Count unique items in array-based fields across all MongoDB documents?
- Summing all the unique values of an array - JavaScript
- Combine unique items of an array of arrays while summing values - JavaScript
- Count unique elements in array without sorting JavaScript
- Remove duplicate items from an array with a custom function in JavaScript
- JavaScript Count the number of unique elements in an array of objects by an object property?
- Count the number of items in an array in MongoDB?
- Finding unique string in an array in JavaScript
- Counting unique elements in an array in JavaScript
- How to get all unique values in a JavaScript array?
- Extract unique values from an array - JavaScript
- Unique pairs in array that forms palindrome words in JavaScript
- Count by unique key in JavaScript
- Count of pairs in an array that have consecutive numbers using JavaScript
- Algorithm to get the combinations of all items in array JavaScript

Advertisements