/  Technology   /  Remove a specific item from an array in Javascript

Remove a specific item from an array in Javascript


In javascript we have different methods to remove an element from an array jere we are using the splice method to remove existing elements and/or adding new elements

Using the indexing method we can remove any particular element from the array. Such as

    <p>Remove elements from array in JavaScript.</p>
      var arr = [3, 6, 8];
      var index = arr.indexOf(6);
      if (index > -1) {
        arr.splice(index, 1);

 In the above code we have declared an array =[3,6,8] which an indexing of [0,1,2].

Using The indexOf() method which returns the first index at which a given element can be found in the array, or -1 if it is not present. Next we have passed the if condition where index is greater than -1 return arr.splice(index,1) that is remove the 1st index element from the array.

Then when we console log arr we get the array without the 1st element.

[3,8] .

The Splice()  method adds and/or removes array elements. This method overwrites the original array.



Leave a comment