JavaScript - Remove n Elements From End Array
Here are the different methods to remove n elements from the end of a given array in JavaScript
1. Using splice() Method
splice() method is used to modify an array by adding or removing elements from it. It accepts the index from which the modification has to be made and the number of elements to delete.
let a = ["a", "b", "c", "d"];
const n = 2;
const rem = (a, n) => {
a.splice(-n, n);
return a;
};
const res = rem([...a], n);
console.log(res);
Output
[ 'a', 'b' ]
In this example, a.splice(-n, n) removes n elements starting from the -n index.
2. Using pop() Method
The pop() method is used to remove the last element from the array.
let a = ["a", "b", "c", "d"];
const n = 2;
const rem = (a , n) => {
const copy = [...a];
for (let i = 0; i < n; i++) {
copy.pop();
}
return copy;
};
const res = rem(a, n);
console.log(res);
Output
[ 'a', 'b' ]
In this example
- pop() removes the last element of the array.
- The loop runs n times to remove the desired number of elements.
3. Using Array.prototype.filter()
The filter() method can selectively keep elements up to a specific index.
let a = ["a", "b", "c", "d"];
const n = 2;
const rem = (a, n) => {
return a.filter((_, index) => index < a.length - n);
};
const res = rem(a, n);
console.log(res);
Output
[ 'a', 'b' ]
In this example
- filter() iterates through the array, including elements whose index is less than array.length - n.
- This method does not modify the original array.
4. Using Array slice() method
The Slice() method returns a new array containing a portion of the array on which it is implemented. The original remains unchanged.
let a = ["a", "b", "c", "d"];
const n = 2;
const rem = (a, n) => {
return a.slice(0, -n);
};
const res = rem(a , n);
console.log(res);
Output
[ 'a', 'b' ]
In this example, a.slice(0, -n) extracts elements from the start of the array up to array.length - n.
5. Using the length Property
The length property can be directly modified to truncate the array.
let a = [1, 2, 3, 4, 5, 6, 7, 8, 9];
let del = 4;
a.length = a.length - del;
console.log("Modified Array:", a);
Output
Modified Array: [ 1, 2, 3, 4, 5 ]
In this example
- Reducing the length property of the array truncates its elements.
- This method modifies the array if used directly, so a copy is recommended.
Choosing the Right Approach
Approach | Use Case | Modifies Original Array? |
---|---|---|
slice() | Preferred for immutability | No |
splice() | When modifying the original array | Yes |
filter() | Functional programming style | No |
pop() Loop | Iterative removal of elements | No |
length Property | Direct truncation of array size | Yes |
- Use slice() or filter() for immutable operations.
- Use splice() or length when modifying the original array is acceptable.
- For iterative needs, pop() works well.