Delete Element Inside an Array in JavaScript

To remove an element from the middle of an array at a given index, we use the splice function as below. For example, to delete at index 2:

const arr = [1, 2, 3, 4, 5]
arr.splice(2, 1)
console.log(arr)

Result:

[ 1, 2, 4, 5 ]

In general, to delete an element at a specific index:

const deleteAtIndex = (arr, index) => {
  arr.splice(index, 1)
}

arr = [1, 2, 3, 4, 5]
deleteAtIndex(arr, 2)
console.log(arr)

Result:

[ 1, 2, 4, 5 ]

 

The following are all options that one my think of that do not do what we want.

Using the delete operator leaves a gap inside the array:

const arr = [1, 2, 3, 4, 5]
delete arr[2]
console.log(arr)

Result:

[ 1, 2, <1 empty item>, 4, 5 ]

Attempting to set the element to null or undefined also does not remove an element; it merely sets the reference at that location to null or undefined:

const arr = [1, 2, 3, 4, 5]
arr[2] = undefined
console.log(arr)

Result:

[ 1, 2, undefined, 4, 5 ]

Leave a Reply

Your email address will not be published. Required fields are marked *