Removing identical entries from an array keeping its length same - 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 four duplicate values, we have to remove them all and insert four empty strings at the end.

Understanding the Problem

The goal is to:

  • Remove duplicate elements from the array
  • Keep only the last occurrence of each element
  • Maintain the original array length by adding empty strings

Example

Following is the code ?

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 function uses reduce() to iterate through the array:

  1. Check for duplicates: array.lastIndexOf(val) === ind returns true only for the last occurrence of each element
  2. Keep unique elements: Last occurrences are added to the res array
  3. Count duplicates: Earlier occurrences increment the count
  4. Add empty strings: " ".repeat(count).split(" ") creates an array of empty strings equal to the number of removed duplicates

Alternative Approach Using Set

const removeDeleteAndInsert = arr => {
    const originalLength = arr.length;
    const uniqueElements = [...new Set(arr.reverse())].reverse();
    const duplicateCount = originalLength - uniqueElements.length;
    
    return uniqueElements.concat(new Array(duplicateCount).fill(''));
};

const testArray = [1,2,3,1,2,3,2,2,3,4,5,5,12,1,23,4,1];
console.log(removeDeleteAndInsert(testArray));
[
   23, 12,  5,  4,  3,  2,  1,
   '',  '', '', '', '', '', '',
   '',  '', '', ''
]

Conclusion

Both methods effectively remove duplicates while maintaining array length. The first approach preserves the order of last occurrences, while the Set-based method is more concise but may change element ordering.

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

188 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements