Changing an array in place using splice() JavaScript

The splice() method allows you to modify arrays in place by removing, adding, or replacing elements. This article demonstrates how to use splice() to remove duplicate elements that exceed a specified count limit.

The Problem

We need to write a function that takes an array and a number n, then removes elements that appear more than n times while preserving the order of remaining elements.

Solution Using splice()

We'll track element counts using a hashmap and use splice() to remove excess occurrences during iteration:

const arr = [7, 26, 21, 41, 43, 2, 26, 24, 10, 26, 10, 10, 24, 35, 35,
35, 43, 26, 41, 7, 24, 24, 21, 24, 10, 35, 10, 7, 24, 7, 35, 26, 41,
35, 2, 43, 24, 2, 41, 26, 41, 7, 7, 26, 2, 10, 43, 10, 35, 41, 24, 7,
2, 2, 7, 2, 26, 24, 26, 43, 43, 21, 10, 28, 10];

const array = [12, 4, 2, 12, 32, 21, 67, 4, 32, 5];

const deleteExtra = (arr, n) => {
    const map = {};
    for(let i = 0; i < arr.length; i++){
        if(map[arr[i]]){
            if(map[arr[i]] >= n){
                arr.splice(i, 1);
                i--; // Adjust index after removal
            } else {
                map[arr[i]]++;
            }
            continue;
        }
        map[arr[i]] = 1;
    }
};

deleteExtra(array, 1);
deleteExtra(arr, 2);
console.log("Array with max 1 occurrence:");
console.log(array);
console.log("Array with max 2 occurrences:");
console.log(arr);
Array with max 1 occurrence:
[
  12, 4, 2, 32,
  21, 67, 5
]
Array with max 2 occurrences:
[
  7, 26, 21, 41, 43, 2, 26,
  24, 10, 10, 24, 35, 35, 43,
  41, 7, 21, 2, 28
]

How It Works

The algorithm uses these key steps:

  • Count tracking: A hashmap stores the count of each element encountered
  • Excess removal: When an element's count reaches the limit n, splice(i, 1) removes it
  • Index adjustment: After removal, i-- prevents skipping the next element
  • In-place modification: The original array is modified directly using splice()

Key Points About splice()

  • splice() modifies the original array and returns the removed elements
  • When removing elements during iteration, always adjust the loop index
  • The method preserves the order of remaining elements

Conclusion

Using splice() with proper index management allows efficient in-place array modification. This approach maintains element order while removing duplicates that exceed the specified count limit.

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

224 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements