Wednesday, August 8, 2018

Remove a given element from an array in JavaScript?


Remove a given element from an array in JavaScript?

First of all we need to find the index of the given element in the array. we can find the index of element using array.indexOf() method.  it returns the first occurrence in the array or it returns -1 , if element is not present in the array. 
  for example , var list = [2,4,6,8,10]
                         var index = list.indexOf(4)   // returns 1

So, now we know the index of given number. 
After,  we will use array.splice() method to remove the element. 
Splice method can be used to add (or remove) element to (or from )
array, and it returns the removed elements. 


if the index is not -1, it means element is present in array.
Using splice method, we will delete remove the number.
   if(index>-1){
   list.splice(index,1)   // 1 represent number of elements to delete


References:


No comments:

Post a Comment