Skip to main content

< Back to Data Structures and Algorithms

LeetCode 27 · Arrays

Remove Element

Removes every copy of a value from an array in place, splicing each out, and returns how many are left.

Step through it

Examples
Edge cases
nums
  1. 30
  2. 21
  3. 22
  4. 33

val = 3

Step 0 of 14

Output

Running… play or step to the end.

The code

/**
 * Remove all occurences of a given number from an integer array.
 * @param {number[]} nums
 * @param {number} val
 * @return {number}
 */
 const removeElement = (nums, val) => {
    // O(n) loop over every item in the integer array.
    for (let i=0; i < nums.length; i++) {
        // The current value matches the value to remove.
        if (nums[i] === val) {
            // Remove the item from the array.
            nums.splice(i, 1)
            // Decrement the iteration counter since the array has shifted left.
            i--
        }
    }
        
    // All 'val' have been removed from the integer array.
    return nums.length
}

View it on GitHub (opens in a new tab)