Removing duplicates and inserting empty strings 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.

Problem Description

If we find 4 duplicate values we have to remove them all and insert four empty strings at the end. This maintains the original array length while eliminating duplicates.

How It Works

The algorithm uses reduce() to iterate through the array. For each element, it checks if the current index matches the last occurrence using lastIndexOf(). If yes, it's the final occurrence and gets added to the result. If no, it's a duplicate and increments the count.

Example

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,
  '', '', '', '', '', '', '',
  '', '', '', ''
]

Step-by-Step Breakdown

Let's trace through with a smaller example:

const smallArr = [1, 2, 1, 3, 2];
console.log("Original array:", smallArr);
console.log("Result:", deleteAndInsert(smallArr));

// Let's see the count of duplicates
const duplicateCount = smallArr.length - [...new Set(smallArr)].length;
console.log("Duplicates removed:", duplicateCount);
Original array: [ 1, 2, 1, 3, 2 ]
Result: [ 3, 2, 1, '', '' ]
Duplicates removed: 2

Alternative Approach Using Set

Here's a simpler implementation using Set for comparison:

const deleteAndInsertSimple = arr => {
    const unique = [...new Set(arr)];
    const duplicateCount = arr.length - unique.length;
    const emptyStrings = new Array(duplicateCount).fill('');
    return [...unique, ...emptyStrings];
};

const testArray = [1, 2, 3, 1, 2, 4];
console.log("Simple approach:", deleteAndInsertSimple(testArray));
Simple approach: [ 1, 2, 3, 4, '', '' ]

Comparison

Method Order Preserved Complexity Readability
Original (lastIndexOf) Last occurrence kept O(n²) Complex
Set-based First occurrence kept O(n) Simple

Conclusion

Both approaches successfully remove duplicates and add empty strings to maintain array length. The Set-based method is more efficient and readable, while the original preserves the last occurrence of each element.

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

348 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements