Find the least duplicate items in an array JavaScript

We are required to write a JavaScript function that takes in an array of literals which may contain some duplicate values.

The function should return an array of all those elements that are repeated for the least number of times.

For example? If the input array is ?

const arr = [1,1,2,2,3,3,3];

Then the output should be ?

const output = [1, 2];

because 1 and 2 are repeated for the least number of times (2)

Example

const arr = [1,1,2,2,3,3,3];

const getLeastDuplicateItems = (arr = []) => {
    const hash = Object.create(null);
    let keys, min;
    
    arr.forEach(el => {
        hash[el] = hash[el] || {
            value: el, 
            count: 0 
        };
        hash[el].count++;
    });
    
    keys = Object.keys(hash);
    keys.sort(function (el, b) {
        return hash[el].count - hash[b].count;
    });
    
    min = hash[keys[0]].count;
    
    return keys.filter(el => {
        return hash[el].count === min;
    }).map(el => {
        return hash[el].value;
    });
}

console.log(getLeastDuplicateItems(arr));

Output

And the output in the console will be ?

[ 1, 2 ]

How It Works

The function counts the frequency of each element using a hash object, sorts elements by their count, finds the minimum count, and returns all elements with that minimum frequency. The algorithm ensures we get all elements that appear the least number of times in the array.

Conclusion

This approach efficiently finds the least duplicate items by counting frequencies and filtering by minimum count. It handles arrays with mixed data types and returns all elements with the same lowest frequency.

Updated on: 2026-03-15T23:19:00+05:30

475 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements