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

How do I unset an element in an array in javascript?

Today I'm going to talk about how do you unset an element from an array? Unsetting means removing or deleting a particular item from an array.

The easiest way to unset elements from an array is by using the splice() method. This method allows you to delete items at any index within your specified range.

To use this method, all you have to do is specify which index position should be removed along with its length. For example, if we want to remove two items starting at index 3 then our code would look something like this:

myArr.splice(3,2); 

The next step is finding out which index of the array holds the element that needs removed. The easiest way of doing this is by looping through each item in the array until its index matches what was provided as input for removal.

<script>
  let myArr = ['red', 'green', 'blue', 'yellow'];
      for (let i = 0; i < myArr.length; i++) {  
        if(myArr[i] == 'blue') {     
          myArr.splice(i,1)
          console.log(myArr)
        }  
      }   
</script>

Once we know which index contains our target value, we can use the splice() method to remove the item form its original array.

save
listen
AI Answer
Write Your Answer
loading
back
View All