How to remove a specific item from a Javascript array

How would you go about removing a specific element from an array using vanilla Javascript?

There’s probably multiple ways to solve this trivial problem. Here’s how I would remove the element “apple” from the following array.

let arr = ["oranges", "banana", "apple", "mango", "watermelon"];

1. Find the index corresponding to the “apple” element using the indexOf function.

let idx = arr.indexOf("apple");

2. Use the splice function to remove the element at the identified index from the array. The splice function takes two arguments: the first argument specifies the index to remove elements from, while the second argument specifies the number of elements to be removed.

arr.splice(idx, 1);
console.log(arr);
// ["oranges", "banana", "mango", "watermelon"]

It should be noted that the splice function modifies the array in place, and returns the modified array. This means that it directly operates on the input array without creating and returning a new array with the required changes.

For the sake of completeness, here is a function that will get the job done for you:

function removeItemFromArray(arr, value) {   
  let idx = arr.indexOf(value);   
  if (index > -1) {     
    arr.splice(index, 1);   
  }   
  return arr; 
}

Leave a Reply

Your email address will not be published. Required fields are marked *

(Required)