How To Delete Element From Array In Javascript

In this blog post, we are going to discuss various methods to delete elements from an array in JavaScript. Some of these methods include pop(), shift(), splice(), and using the delete operator.

Method 1: Using pop() to Remove the Last Element of an Array

The pop() method removes the last element of an array and returns that element. This method changes the length of the array. Here’s an example:

let fruits = ['apple', 'banana', 'cherry'];
let removedElement = fruits.pop();

console.log(removedElement); // Output: 'cherry'
console.log(fruits); // Output: ['apple', 'banana']

Method 2: Using shift() to Remove the First Element of an Array

The shift() method removes the first element of an array and returns that removed element. This method changes the length of the array. Here’s an example:

let fruits = ['apple', 'banana', 'cherry'];
let removedElement = fruits.shift();

console.log(removedElement); // Output: 'apple'
console.log(fruits); // Output: ['banana', 'cherry']

Method 3: Using splice() to Remove Elements from an Array

The splice() method is very versatile and can be used to add and/or remove elements from an array. The syntax for the splice method is as follows:

array.splice(start[, deleteCount[, item1[, item2[, ...]]]]);

The start parameter is the index at which to start changing the array. The deleteCount parameter is an integer indicating the number of elements to remove from the array. If you want to add elements to the array, you can provide them as item1, item2, and so on.

Here’s an example of removing one element from the array using the splice method:

let fruits = ['apple', 'banana', 'cherry'];
let removedElements = fruits.splice(1, 1);

console.log(removedElements); // Output: ['banana']
console.log(fruits); // Output: ['apple', 'cherry']

In this example, we start at index 1 and remove 1 element from the array.

Method 4: Using the delete Operator to Remove an Element

The delete operator allows you to remove an element from an array without changing the length of the array. This will leave a hole in the array, and the deleted element will become undefined. Here’s an example:

let fruits = ['apple', 'banana', 'cherry'];
delete fruits[1];

console.log(fruits); // Output: ['apple', undefined, 'cherry']

As you can see, the delete operator is not ideal for removing elements from an array because it leaves holes in the array, which could lead to unexpected behavior in your code.

Conclusion

In this blog post, we discussed various methods to delete elements from an array in JavaScript, such as pop(), shift(), splice(), and the delete operator. Depending on your specific use-case, one of these methods should help you delete elements from your array in the most efficient manner.