Manipulating arrays in JavaScript is a common task, and one of the most frequently used operations is removing elements from the end of an array. In this post, we will show you how to remove the last 3 elements from an array using JavaScript. We will cover different methods, and provide examples to help you understand the process.
slice()
methodThe slice()
method is used to extract a portion of an array and return it as a new array. To remove the last 3 elements from an array, you can use the slice()
method in the following way:
let myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
myArray = myArray.slice(0, -3);
console.log(myArray); // output: [1, 2, 3, 4, 5, 6]
The above code will remove the last 3 elements, [7, 8, 9], from the array myArray
, and return a new array with the remaining elements.
splice()
methodThe splice()
method is used to add or remove elements from an array. To remove the last 3 elements from an array, you can use the splice()
method in the following way:
let myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
myArray.splice(-3, 3);
console.log(myArray); // output: [1, 2, 3, 4, 5, 6]
The above code will remove the last 3 elements, [7, 8, 9], from the array myArray
. The first argument, -3, is the index of the last element, and the second argument, 3, is the number of elements to remove.
pop()
methodThe pop()
method is used to remove the last element from an array and return it. To remove the last 3 elements from an array, you can use the pop()
method in a loop:
let myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
for (let i = 0; i < 3; i++) {
myArray.pop();
}
console.log(myArray); // output: [1, 2, 3, 4, 5, 6]
The above code will remove the last 3 elements, [7, 8, 9], from the array myArray
by using the pop()
method 3 times in a loop.
Conclusion:
There are numerous ways to remove the last three members from an array with JavaScript. This can be accomplished using the slice()
, splice()
, and pop()
functions, among others. We trust that this article has made it clear how to eliminate the final three entries from an array in JavaScript.
Leave a Reply