Remove elements from javascript array

Posted on Sept. 27, 2018
javascript
1306

The main aim of this article is to show case the ways to remove elements from a javascript array

ar = [1,2,3,4,5,6]

Procedure1 : splice is a built in method of javascript array. This is the best method to remove elements . It just takes two parameters index defines where to starts from and the next is the number defines how many elements to be removed. 

          ar.splice(ind, noOfElementsToRemove)

Ex:

  1. If a user want to remove 2nd element from the ar. Ex :ar.splice(1, 1)
  2. If a user want to remove 2nd and 3rd elements from the ar. Ex: ar.splice(1, 2)

Procedure2 : Delete the element without splice method 
              elementToRemove = 3
                index = a.indexOf(elementToRemove)
                c1 =  a.slice(0,index)
                c2 = a.slice(index+1, ar.length)
                c1.concat(c2)

                console.log(c1)

Procedure3 : Usually helps while deleting json keys. When we try to remove the element from array using delete keyword it will remove the element but the array length is constant and moreover replace the removed element with undefined.

Ex: delete ar[1]

         If we try to print the ar it returns as [1, undefined, 3, 4, 5, 6]

Procedure4 : pop

Just helps to remove element from the end

Ex: ar.pop()

Just removes the last element that is 6 and return the 5 length array

Procedure5 : shift

Helps to remove element from the first

Ex: ar.shift()

Just removes the first element that is 1 and return the 5 length array




0 comments

Please log in to leave a comment.