Web Tools Table Maker3schools TranslateImage CompressorFavicon Icon GeneratorCrop & Resize Image
Apu
Apu February 15, 2023 › #Array #HowTo

How to remove element from JavaScript array by value

Removing an element from a JavaScript array by index number is easy. You can use the JavaScript built-in method splice(). The example is given below.

<script>
  const myArray = ['Red', 'Green' , 'Blue', 'Yellow'];   
      myArray.splice(2,1)
      console.log(myArray)
</script>

Remove element from JavaScript array by value #

But in this article, I will talk about how to remove an element from a JavaScript array by value.

You can use the filter() method which creates a new version of your original JavaScript array without including any item whose condition evaluates false according to your custom function's logic :

<script>
 const myArray = ['Red', 'Green' , 'Blue', 'Yellow'];   
 const newArray = myArray.filter((element) => element !== 'Blue');    
 console.log(newArray)
</script>
save
listen
AI Answer
1 Answer
Write Your Answer
  1. You can also use the splice() method and a loop to remove items from an array by value in JavaScript. The splice() method takes two parameters, the index of the element you wish to remove and the number of elements to remove.
    The loop will iterate over the array and find the index of the element that matches the value you are looking for. Once the index is found, the splice() method can be used to remove the element at that index.
    <script>
    let myArr = ["one", "two", "three", "four", "five"];
    let value = "two";
      for (let i = 0; i < myArr.length; i++) {
    if (myArr[i] === value) {
        myArr.splice(i, 1);
        break;
    }
    }
    console.log(myArr)
    </script>

    This will remove the element with the value two and return it in an array. The remaining elements in the array will be :
    0:one
    1:three
    2:four
    3:five
    Reply Delete
    Share
loading
back
View All