Completely removing duplicate items from an array in JavaScript

We are required to write a function that takes in an array and returns a new array that have all duplicate values removed from it.

The values that appeared more than once in the original array should not even appear for once in the new array.

For example, if the input is:

const arr = [23,545,43,232,32,43,23,43];

The output should be:

[545, 232, 32]

Understanding indexOf() vs lastIndexOf()

  • Array.prototype.indexOf() ? Returns the index of first occurrence of searched element if it exists, otherwise -1.

  • Array.prototype.lastIndexOf() ? Returns the index of last occurrence of searched element if it exists, otherwise -1.

The key insight is: if indexOf() and lastIndexOf() return the same index for an element, it means that element appears only once in the array.

Method 1: Using indexOf() and lastIndexOf()

const arr = [23, 545, 43, 232, 32, 43, 23, 43];

const deleteDuplicate = (arr) => {
    const output = arr.filter((item, index, array) => {
        return array.indexOf(item) === array.lastIndexOf(item);
    });
    return output;
};

console.log(deleteDuplicate(arr));
[ 545, 232, 32 ]

Method 2: Using Map to Count Occurrences

const arr = [23, 545, 43, 232, 32, 43, 23, 43];

const removeDuplicates = (arr) => {
    const countMap = new Map();
    
    // Count occurrences
    arr.forEach(item => {
        countMap.set(item, (countMap.get(item) || 0) + 1);
    });
    
    // Filter elements that appear only once
    return arr.filter(item => countMap.get(item) === 1);
};

console.log(removeDuplicates(arr));
[ 545, 232, 32 ]

Comparison

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

How It Works

The first method compares the first and last occurrence indices of each element. If they match, the element appears only once. The second method counts occurrences using a Map and filters elements with count = 1.

Conclusion

Both methods effectively remove all duplicate elements from an array. The indexOf/lastIndexOf approach is simpler but slower, while the Map method is more efficient for large arrays.

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

353 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements