OneBite.Dev - Coding blog in a bite size

remove a specific element from an array in Javascript

Code snippet on how to remove a specific element from an array in Javascript

  var myArray = [1, 2, 3, 4, 5]; 
  var elementToRemove = 3;
  var index = myArray.indexOf(elementToRemove);

  if (index > -1) {
    myArray.splice(index, 1);
  }

This code checks if the element to remove (in this case 3) is located in a given array of integers (in this case [1, 2, 3, 4, 5]). The indexOf method looks through the array for the element, and if it is present, it returns the index of the element. The if statement checks if the index is greater than -1, which means that the element is in the array. Then, the splice method is used to remove the element from the array. The splice method needs two arguments - the index of the element to remove and the number of elements to remove (in this case, just one element is removed). Once the splice method is executed, the element is removed from the array.

javascript