There are different ways to remove an element from a specific position in an array in JavaScript.
1. Using splice() Method
The splice()
method is the most direct and versatile way to remove an element from a specific position. It modifies the original array.
let arr = [10, 20, 30, 40, 50];
arr.splice(2, 1); // Remove 1 element at index 2
console.log(arr); // Output: [10, 20, 40, 50]
2. Using filter() Method
The filter()
method creates a new array that excludes the element at a specific position. This approach does not modify the original array.
let arr = [10, 20, 30, 40, 50];
let newArr = arr.filter((_, index) => index !== 2);
console.log(newArr); // Output: [10, 20, 40, 50]
console.log(arr); // Output: [10, 20, 30, 40, 50]
3. Using slice() Method
The slice()
method creates a new array by slicing parts of the original array before and after the target index.
let arr = [10, 20, 30, 40, 50];
let newArr = [...arr.slice(0, 2), ...arr.slice(3)];
console.log(newArr);
// Output: [10, 20, 40, 50]
4. Using Destructuring Assignment
Destructuring provides a modern and concise way to remove an element while creating a new array.
let arr = [10, 20, 30, 40, 50];
let [first, second, , ...rest] = arr;
let newArr = [first, second, ...rest];
console.log(newArr);
// Output: [10, 20, 40, 50]
5. Using for Loop
Using a loop gives full control over the process of removing an element.
let arr = [10, 20, 30, 40, 50];
let newArr = [];
for (let i = 0; i < arr.length; i++) {
if (i !== 2) {
// Skip the element at index 2
newArr.push(arr[i]);
}
}
console.log(newArr);
// Output: [10, 20, 40, 50]
6. Using reduce() Method
The reduce()
method can be used to build a new array while skipping the element at a specific index.
let arr = [10, 20, 30, 40, 50];
let newArr = arr.reduce((acc, num, index) => {
if (index !== 2)
acc.push(num);
return acc;
}, []);
console.log(newArr); // Output: [10, 20, 40, 50]
7. Using Array.from() Method
The Array.from()
method can be paired with a mapping function to exclude the element at a specific index.
let arr = [10, 20, 30, 40, 50];
let newArr = Array.from(arr, (num, index) => (index === 2 ? undefined : num)).filter(Boolean);
console.log(newArr);
// Output: [10, 20, 40, 50]