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

How to remove multiple elements from array in JavaScript.

Today I'm going to show you how to remove multiple elements from an array in JavaScript. Let's get started!

The first step is finding the index of each element that you want to delete. To do this, use the indexOf() method which will return -1 if it doesn't find anything matching your criteria.

<script>
 let myArray = [1 , 2 , 3 , 4 , 5];
 let myIndex = myArray.indexOf(3);
 console.log(myIndex);  // output : 2
</script>

Next we want to actually remove this item from our original array using the splice() method. The splice() method takes two arguments; The first argument tells us where we are starting our removal and second one tells us how many elements should be removed after that point.

myArray.splice(myIndex ,1);// removes one element starting at position given by myIndex

Now if we have more than one item that needs deleting then simply loop through them all like this example below.

<script>
 let myArray = [1 , 2 , 3 , 4 , 5, 3, 6];
 for(let i=0 ;i<myArray.length; i++ ){    
    if(myArray[i] === 3){
       myArray.splice(i,1);     
    } 
 }
 console.log(myArray) // output : [1,2,4,5,6]
</script>
save
listen
AI Answer
Write Your Answer
loading
back
View All