How to remove all occurences of an element from an array in JavaScript

Last updated on Jun 18, 2022 by Suraj Sharma


In this tutorial you will learn how you can remove all occurrences of an element from an array in JavaScript without using any extra space i.e; in O(1) space complexity.


To solve this we are going to use two pointers and iterate through the array to remove all occurrences of an element.


Solution

  var removeElement = function(nums, val) {
      if (!nums.length)
          return 0
      let j = 0;
      for (let i=0;i<nums.length;i++) {
          if (nums[i] !== val) {
              nums[j++] = nums[i]
          }
      }
      return j
  };

  removeElement([3,2,2,3], 3);
  // [2,2]


Related Solutions


Rate this post


Suraj Sharma is the founder of Future Gen AI Services. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.