- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 }
Advertisements
To Continue Learning Please Login
Login with Google