DEV Community

Cover image for Delete an element in array
Nishant Patil
Nishant Patil

Posted on • Edited on

Delete an element in array

Theory :
Consider a Array declared as
let arr=[1,2,3,4,5]

Suppose we want to delete the element at index 2, that means we have to replace the element at index 3 to position at index 2 and same for all other elements .

Suppose we want to delete the element at index n. We will do this by replacing the element at index n+1 to n, replacing the element at index n+2 to n+1, similarly for all other elements. And once the element is deleted and all other elements are at new place, then we will decrease the length the of array by 1

let data =[30,20,45,76,20,80]; let position =3; for(let i=position; i<data.length-1;i++){ data[i]=data[i+1]; } data.length= data.length-1; 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)