Remove first and last element from an array in JavaScript
This article is about how to remove first or last element from an array in JavaScript using in-built functions like pop(), shift() and splice().
In this article we will learn how to remove the first and last element from an array in JavaScript.
JavaScript have some in-built function which helps us to add or remove elements from an array easily.
Using this methods, we can remove the first or the last element or even an specific element at an given index from an array.
Since this article is about removing the first and last element, we will be using the pop() and shift() method of JavaScript.
array.pop() - Remove Last Element
The pop() method in JavaScript removes the last element from an array and return the removed element.
pop() changes the length of the array.
Lets see the example:
Here we will remove the last element i.e leopard from the animals array.
const animals = ['tiger', 'rhino', 'giraffe', 'camel', 'leopard']; console.log(animals.pop()); // output: "leopard" console.log(animals); // output: Array ['tiger', 'rhino', 'giraffe', 'camel'];
array.shift() - Remove First Element
The shift() method in JavaScript removes the first element from an array and return the element.
shift() changes the length of the array and also the remaining elements index shift down.
Example
const animals = ['tiger', 'rhino', 'giraffe', 'camel', 'leopard']; console.log(animals.shift()); // output: "tiger" console.log(animals); // output: Array [rhino', 'giraffe', 'camel','leopard'];
Related Topics:
Related Posts
Find the average of n numbers using JavaScript
Tutorial to write a JavaScript function to find the average of n numbers of items in an Array using JavaScript.
Best way - Split an array into half in Javascript
To divide an single array into half i.e into two different arrays without modifying the original array we can use Array.slice() method in JavaScript.
Merge Two Arrays and Remove Duplicates - JavaScript
Tutorial on how to merge two or more array and remove duplicates in JavaScript.
How to multiply all numbers in an array using JavaScript
Quick tutorial on how to multiply all the elements in an array using iterative i.e loop and reduce method in JavaScript.
