Anjan Dutta

Remove a specific item from an array in 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.

1const todo_list = [11, 4, 90, 32];
2const item_index = todo_list.indexOf(90); //finding the position
3
4if (item_index> -1) {
5 array.splice(item_index, 1);
6}
7
8console.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.

Remove an 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.

1var arr_main = [5, 10, 34, 23, 5, 15, 5];
2
3function rem(arr, num) {
4 const index = arr.indexOf(num);
5 if (index>-1) {
6 arr.splice(index, 1);
7 return rem(arr, num);
8 } else {
9 return arr;
10 }
11}
12
13const result_arr = rem(arr_main, 5);
14console.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.