Last Updated : 14 Nov, 2024
These are the following ways to delete elements from JavaScript arrays:
1. Using shift() method - Mostly UsedThe shift() method removes the first element from the array and adjusts its length.
JavaScript
const a = [1, 2, 3, 4];
// Remove the first element
a.shift();
console.log(a);
2. Using splice() method
The splice() method is used to remove elements by specifying index and count.
JavaScript
const a = [1, 2, 3, 4];
// Remove the first element
a.splice(0, 1);
console.log(a);
3. Using Destructuring Assignment
Array destructuring is used to extract the first element and create a new array with the rest elements.
JavaScript
const a1 = [1, 2, 3, 4];
// Skip the first element
const [, ...a2] = a1;
console.log(a2);
4. Using Custom Method
The idea is to start from the second element and shift all the elements one position to the left. After shifting all the elements, reduce the array size by 1 to remove the extra element at the end.
JavaScript
const a = [1, 2, 3, 4];
for (let i = 0; i < a.length - 1; i++) {
a[i] = a[i + 1];
}
// Adjust length to "delete" last element
a.length = a.length - 1;
console.log(a);
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4