Skip to content

JavaScript remove item from array by value

  • by

In JavaScript, you can remove an item from an array by its value using either the Array.filter() method or the indexOf() method combined with the splice() method.

The filter() method creates a new array that only includes the items from the original array that pass a condtions, while the indexOf() method returns the index of the first occurrence of the specified value in an array. The splice() method removes elements from an array and returns the removed elements.

Using Array.filter() method:

let newArray = originalArray.filter(element => element !== valueToRemove);

Using Array.indexOf() and Array.splice() methods:

let index = originalArray.indexOf(valueToRemove);
if (index > -1) {
    originalArray.splice(index, 1);
}

JavaScript removes the item from the array by value example

Simple example code.

<!DOCTYPE html>
<html>
  <body>    
    <script>
    let myArray = ['apple', 'banana', 'orange', 'grape'];
    let itemToRemove = 'orange';

    myArray = myArray.filter(item => item !== itemToRemove);

    console.log(myArray);

    </script>
  </body>
</html>

Yes, you can also use the indexOf() method to remove an item from an array in JavaScript by its value.

let myArray = ['apple', 'banana', 'orange', 'grape'];
let itemToRemove = 'orange';

let index = myArray.indexOf(itemToRemove);
if (index > -1) {
  myArray.splice(index, 1);
}

console.log(myArray);

Output:

JavaScript remove item from array by value

Comment if you have any doubts or suggestions on this Js array topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading