- 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
Count unique elements in array without sorting JavaScript
Let’s say, we have an array of literals that contains some duplicate values −
const arr = ['Cat', 'Dog', 'Cat', 'Elephant', 'Dog', 'Grapes', 'Dog', 'Lion', 'Grapes', 'Lion'];
We are required to write a function that returns the count of unique elements in the array. Will use Array.prototype.reduce() and Array.prototype.lastIndexOf() to do this −
Example
const arr = ['Cat', 'Dog', 'Cat', 'Elephant', 'Dog', 'Grapes', 'Dog', 'Lion', 'Grapes', 'Lion']; const countUnique = arr => { return arr.reduce((acc, val, ind, array) => { if(array.lastIndexOf(val) === ind){ return ++acc; }; return acc; }, 0); }; console.log(countUnique(arr));
Output
The output in the console will be −
5
Advertisements
To Continue Learning Please Login
Login with Google