DEV Community

Cover image for How to remove specific element occurrence from an Array.
michael-2509
michael-2509

Posted on

How to remove specific element occurrence from an Array.

QUESTION
Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The relative order of the elements may be changed.

STEP
Since we want to remove all occurrences of a particular value from the array, we can use this approach

  • Loop through the array

while(condition){}

The while method reiterates sets of action within the curly braces until conditions are met or becomes false.

For the condition to remain true, the while loop checks if the integer value can be found in the array, otherwise the condition becomes false and the loop is exited. So I used the includes method on the array to achieve this.

  • Remove the specific integer val that occurs in array

array.splice("start", "deleteCount")

To remove ocurrences of the specific value, i used the splice array method and indexOf method to create the logic to remove the values.

The splice takes in a first argument(start) which in this case would be the index of the integer value I want to remove and a second value(deleteCount) which I specified to be "1" so just a single element is remove from the array begining from (start)

To determine the (start) value, I used the indexOf method. indexOf returns the index of the first occurrence of a specific value within the array.

How the Code Runs
The while loop checks if the integer value can be found in the array nums. If true, it go ahead to remove the first occurrence of the integer value from the array using splice and indexOf logic, this process repeats itself until the while condition is false.

Final code.

var removeElement = function(nums,
val){ 
    //loop through array 
   while (condition){ 
   //remove element from the array using splice method.
  nums.splice("start",1); } 
    return nums.length; 
};
Enter fullscreen mode Exit fullscreen mode

BONUS
If you ever wonder how this can be applied to a real project.

You can use this approach to filter out specific genre from a list of movie genre on a movie website. Allowing user to remove specific genre they no longer want to see on movies page.

Top comments (0)