- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
- Related Articles
- Sorting array of exactly three unique repeating elements in JavaScript
- Sorting Array without using sort() in JavaScript
- Unique sort (removing duplicates and sorting an array) in JavaScript
- Counting unique elements in an array in JavaScript
- How to count unique elements in the array using java?
- Fetch Second minimum element from an array without sorting JavaScript
- JavaScript Count the number of unique elements in an array of objects by an object property?
- Sorting array according to increasing frequency of elements in JavaScript
- Sorting array based on increasing frequency of elements in JavaScript
- Check if items in an array are consecutive but WITHOUT SORTING in JavaScript
- JavaScript function that should count all unique items in an array
- Sorting an array including the elements present in the subarrays in JavaScript
- Unique number of occurrences of elements in an array in JavaScript
- Comparing array elements keeping count in mind in JavaScript
- Count by unique key in JavaScript

Advertisements