
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Count Unique Elements in Array Without Sorting in 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