Remove duplicates from an array keeping its length same in JavaScript

We have to write a function that takes in an array, removes all duplicates from it and inserts the same number of empty strings at the end.

For example ? If we find 4 duplicate values we have to remove them all and insert four empty strings at the end.

Therefore, let's write the code for this problem ?

Problem Analysis

The task requires us to:

  • Remove duplicate elements from the array
  • Keep only the last occurrence of each element
  • Replace removed duplicates with empty strings
  • Maintain the original array length

Solution Using Array.reduce()

const arr = [1,2,3,1,2,3,2,2,3,4,5,5,12,1,23,4,1];

const deleteAndInsert = arr => {
    const creds = arr.reduce((acc, val, ind, array) => {
        let { count, res } = acc;
        if(array.lastIndexOf(val) === ind){
            res.push(val);
        }else{
            count++;
        };
        return {res, count};
    }, {
        count: 0,
        res: []
    });
    const { res, count } = creds;
    return res.concat(" ".repeat(count).split(" "));
};

console.log(deleteAndInsert(arr));
[
  2, 3, 5, 12, 23, 4, 1,
  '', '', '', '', '', '', '',
  '', '', '', ''
]

How It Works

The solution uses array.lastIndexOf(val) === ind to check if the current element is the last occurrence in the array. If true, it's added to the result; otherwise, the duplicate counter is incremented.

Alternative Approach Using Set

const arr2 = [1,2,3,1,2,3,2,2,3,4,5,5,12,1,23,4,1];

const removeWithSet = arr => {
    // Get unique elements preserving last occurrence order
    const reversed = [...arr].reverse();
    const unique = [...new Set(reversed)].reverse();
    
    const duplicateCount = arr.length - unique.length;
    const emptyStrings = new Array(duplicateCount).fill('');
    
    return unique.concat(emptyStrings);
};

console.log(removeWithSet(arr2));
[
  2, 3, 5, 12, 23, 4, 1,
  '', '', '', '', '', '', '',
  '', '', '', ''
]

Comparison

Method Time Complexity Readability
Array.reduce() O(n²) Complex
Set approach O(n) Cleaner

Conclusion

Both methods effectively remove duplicates while maintaining array length. The Set approach offers better performance and readability for most use cases.

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

251 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements