javascript

Remove a specific item from an array in javascript

Remove a specific item from an array in javascript, a common problem that we face very often. It occurs when we deal with string or integer arrays.

Think of a scenario like this. Let suppose we are using a todo list where each work item is an array element. Now, once we complete any of the work items from the todo list, we have to remove that element from the array of work items.

Here we need a logic to remove a specific item from an array.

In this article, we are going to discuss the things below.

  1. Remove a specific item from an array in javascript.
  2. Remove item with multiple occurrences from an array.

First, we are going to discuss how to remove a single item.

Remove a specific item from an array in javascript.

We have to follow two steps here. At first, we need to find the index of the array item that we are looking to remove. Second, we have to use that position to remove that array item.

The solution is below.

const todo_list = [11, 4, 90, 32];
const item_index = todo_list.indexOf(90); //finding the position

if (item_index> -1) {
  array.splice(item_index, 1);
}

console.log(array); // array = [11, 4, 32] 

The above solution would solve the intended problem. Now let’s take a look at a similar problem but, this time we will be removing a single item with multiple occurrences.

Item with multiple occurrences.

I am using the recursive approach below. But, depending upon the array size, we can use a for or while loop, instead of using a recursive function as well.

var  arr_main = [5, 10, 34, 23, 5, 15, 5];
 
function rem(arr, num) {
  const index = arr.indexOf(num);
  if (index>-1) {
      arr.splice(index, 1);
      return rem(arr, num);
  } else {
      return arr;
  }
}

const result_arr = rem(arr_main, 5);
console.log(result_arr); // [10, 34, 23, 15] 

Okay, I know that the solution looks a bit complex for a simple problem. Let me explain.

In the above solution, I have created a recursive function rem. The function checks and removes an element if found. And, calls itself to check for any more occurrences.

If any item does not match, then it returns the array.

Thanks for reading till here. Please subscribe below if you like my blog.

Leave a Comment

thirty one − twenty two =