Delete first element of an array in JavaScript
This post will discuss how to delete the first element of an array in JavaScript.
Deleting the first element from an array results in deletion of the element at index 0 and shifting the remaining elements to the left. Here are some examples of how to delete the first element from an array in JavaScript given an array:
1. Using shift() function
A simple and efficient way to delete the first element from an array is using the shift() function. It is a built-in function that removes the first element from an array and returns that removed element, and modifies the original array by shifting the remaining elements to the left. This decrements the length of the array by 1. For example, to delete the first element from an array of numbers, we can use the following code:
|
1 2 3 4 5 6 7 |
var arr = [1, 2, 3, 4, 5]; // remove and return the first element var first = arr.shift(); console.log(arr); // [2, 3, 4, 5] console.log(first); // 1 |
2. Using splice() function
The Array.splice() function changes the contents of an array by removing existing elements and/or adding new elements. We can use this function to delete the first element from an array by passing 0 as the start index and 1 as the delete count. The function returns an array of the removed elements, and modifies the original array by shifting the remaining elements to the left. For example, if we have an array [1, 2, 3, 4, 5] and we want to delete the first element, we can do:
|
1 2 3 4 5 6 7 |
var arr = [1, 2, 3, 4, 5]; // remove one element from the beginning var removed = arr.splice(0, 1); console.log(arr); // [2, 3, 4, 5] console.log(removed); // [1] |
3. Using slice() function
The slice() function is a built-in function that returns a shallow copy of a portion of an array into a new array object. We can use it to create a new array without the first element by passing 1 as the start index. This will return an array of the remaining elements, and does not modify the original array. For example:
|
1 2 3 4 5 6 7 |
var arr = [1, 2, 3, 4, 5]; // create a new array without the first element var newArr = arr.slice(1); console.log(arr); // [1, 2, 3, 4, 5] console.log(newArr); // [2, 3, 4, 5] |
That’s all about deleting the first element of an array in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)