Delete an element from array ( Using two traversals and one traversal ) | This function removes an element x from arr [ ] and returns new size after removal . Returned size is n - 1 when element is present . Otherwise 0 is returned to indicate failure . ; If x is last element , nothing to do ; Start from rightmost element and keep moving elements one position ahead . ; If element was not found ; Else move the next element in place of x ; Driver program to test above function ; Delete x from arr [ ]
function deleteElement ( arr , n , x ) { if ( arr [ n - 1 ] == x ) return ( n - 1 ) ; let prev = arr [ n - 1 ] , i ; for ( i = n - 2 ; i >= 0 && arr [ i ] != x ; i -- ) { let curr = arr [ i ] ; arr [ i ] = prev ; prev = curr ; } if ( i < 0 ) return 0 ; arr [ i ] = prev ; return ( n - 1 ) ; } let arr = [ 11 , 15 , 6 , 8 , 9 , 10 ] ; let n = arr . length ; let x = 6 ; n = deleteElement ( arr , n , x ) ; document . write ( " " ) ; for ( let i = 0 ; i < n ; i ++ ) document . write ( arr [ i ] + " " ) ;