Remove all occurrences of a multiple occurring element in an array in JavaScript

We are required to write a JavaScript function that takes in an array of literal values. The array might contain some repeating values. Our function should remove all the values from the array that are repeating. We are required to remove all instances of all such elements.

Problem Understanding

When an element appears multiple times in an array, we want to remove ALL occurrences of that element, not just the duplicates. For example, if 2 appears twice, we remove both instances.

Using filter() with indexOf() and lastIndexOf()

The most efficient approach uses filter() to keep only elements where the first and last occurrence positions are the same:

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

const removeAllInstances = (arr = []) => {
    const filtered = arr.filter(val => {
        const lastIndex = arr.lastIndexOf(val);
        const firstIndex = arr.indexOf(val);
        return lastIndex === firstIndex;
    });
    return filtered;
};

console.log(removeAllInstances(arr));
[ 1, 3, 4 ]

How It Works

For each element, we compare its first occurrence position with its last occurrence position. If they match, the element appears only once and should be kept. If they differ, the element repeats and all instances are filtered out.

Alternative Method: Using Map for Frequency Count

const removeAllInstances2 = (arr = []) => {
    const frequency = new Map();
    
    // Count occurrences
    arr.forEach(val => {
        frequency.set(val, (frequency.get(val) || 0) + 1);
    });
    
    // Keep only elements with frequency 1
    return arr.filter(val => frequency.get(val) === 1);
};

const testArray = [1, 2, 3, 2, 4, 5, 5];
console.log(removeAllInstances2(testArray));
[ 1, 3, 4 ]

Testing with Different Cases

// Test with strings
const stringArray = ['a', 'b', 'c', 'b', 'd'];
console.log("String test:", removeAllInstances(stringArray));

// Test with all unique elements
const uniqueArray = [1, 2, 3, 4, 5];
console.log("All unique:", removeAllInstances(uniqueArray));

// Test with all duplicate elements
const allDuplicates = [1, 1, 2, 2, 3, 3];
console.log("All duplicates:", removeAllInstances(allDuplicates));
String test: [ 'a', 'c', 'd' ]
All unique: [ 1, 2, 3, 4, 5 ]
All duplicates: []

Comparison

Method Time Complexity Space Complexity Readability
indexOf/lastIndexOf O(n²) O(1) High
Map frequency count O(n) O(n) Medium

Conclusion

The indexOf/lastIndexOf method is simpler and more readable for small arrays. For larger datasets, the Map-based frequency counting approach offers better time complexity. Both methods effectively remove all instances of repeating elements.

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

889 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements