Count unique elements in array without sorting JavaScript

When working with arrays containing duplicate values, counting unique elements is a common task. Let's explore different approaches to count unique elements in an array without sorting it first.

Consider this sample array with duplicate values:

const arr = ['Cat', 'Dog', 'Cat', 'Elephant', 'Dog', 'Grapes', 'Dog', 'Lion', 'Grapes', 'Lion'];
console.log('Original array:', arr);
Original array: ['Cat', 'Dog', 'Cat', 'Elephant', 'Dog', 'Grapes', 'Dog', 'Lion', 'Grapes', 'Lion']

Using Array.reduce() and lastIndexOf()

This approach uses lastIndexOf() to identify the last occurrence of each element, ensuring each unique value is counted only once:

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('Unique elements count:', countUnique(arr));
Unique elements count: 5

Using Set Constructor

The most concise approach uses the Set constructor, which automatically removes duplicates:

const arr = ['Cat', 'Dog', 'Cat', 'Elephant', 'Dog', 'Grapes', 'Dog', 'Lion', 'Grapes', 'Lion'];

const countUniqueWithSet = arr => {
    return new Set(arr).size;
};

console.log('Unique elements count using Set:', countUniqueWithSet(arr));
Unique elements count using Set: 5

Using filter() and indexOf()

This method filters elements by keeping only their first occurrence:

const arr = ['Cat', 'Dog', 'Cat', 'Elephant', 'Dog', 'Grapes', 'Dog', 'Lion', 'Grapes', 'Lion'];

const countUniqueWithFilter = arr => {
    return arr.filter((val, ind, array) => array.indexOf(val) === ind).length;
};

console.log('Unique elements count using filter:', countUniqueWithFilter(arr));
Unique elements count using filter: 5

Comparison of Methods

Method Performance Readability Memory Usage
reduce() + lastIndexOf() O(n²) Medium Low
Set constructor O(n) High Medium
filter() + indexOf() O(n²) High Low

Conclusion

The Set constructor approach is the most efficient and readable method for counting unique elements. For smaller arrays, all methods work well, but Set offers the best performance for larger datasets.

Updated on: 2026-03-15T23:18:59+05:30

401 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements