How to remove n elements from the end of a given array in JavaScript ?
In this article, we will learn how to remove the last n elements from the end of the given array in JavaScript. This can be achieved using two approaches:
The splice() method in JavaScript is used to modify an array by adding or removing elements from it. This method accepts the index from which the modification has to be made and the number of elements to delete. The index from which the deletion has to start can be found out by subtracting the number of elements from the length of the array.
Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it's lowest price ever!
Syntax:
array.splice(start, deleteCount);
Example:
HTML
<html> <body> <h1 style="color: green;"> GeeksforGeeks </h1> <b> How to remove n elements from the end of a given array in JavaScript? </b> <script> // Define the array let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]; console.log("Original Array:", arr); // Define the number of elements to remove let elemsToDelete = 3; // Using the splice() method to remove from // the last nth index for n elements arr.splice(arr.length - elemsToDelete, elemsToDelete); console.log("Modified Array:", arr); </script> </body></html> |
Output:
Original Array: [1, 2, 3, 4, 5, 6, 7, 8, 9] Modified Array: [1, 2, 3, 4, 5, 6]
The pop() method in JavaScript is used to remove the last element from the array. This can be repeated in a loop of n iterations to remove the last n elements of the array using the while loop.
Syntax:
array.pop();
Example:
HTML
<html> <body> <h1 style="color: green;"> GeeksforGeeks </h1> <b> How to remove n elements from the end of a given array in JavaScript? </b> <script> // Define the array let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]; console.log("Original Array:", arr); // Define the number of elements to remove let elemsToDelete = 5; // Loop for the number of elements // to delete while (elemsToDelete--) // Pop the last element from the // end of the array arr.pop(); console.log("Modified Array:", arr); </script> </body></html> |
Output:
Original Array: [1, 2, 3, 4, 5, 6, 7, 8, 9] Modified Array: [1, 2, 3, 4]


