In JavaScript, splice() directly modifies the original array. If you want to remove elements while keeping the original array unchanged, you can create a new array using methods such as slice(), filter(), and the spread operator.
- Creates a new array instead of modifying the original.
- Useful when working with immutable data.
- Different methods can be used depending on whether removal is based on indexes or conditions.
Approach 1: Using slice() and concat()
The combination of slice() and concat() can remove specific elements by combining the portions of the array before and after the elements to be removed.
Example: Remove the elements at indexes 1 and 2 without modifying the original array.
const a1 = [1, 2, 3, 4, 5];
// Remove elements at index 1 and 2
const a2 = a1.slice(0, 1).concat(a1.slice(3));
console.log(a2);
console.log(a1);
Output
[ 1, 4, 5 ] [ 1, 2, 3, 4, 5 ]
Approach 2: Using filter() Method
The filter() method creates a new array containing only the elements that satisfy a specified condition. It does not modify the original array.
Example: Use filter() to remove the elements at indexes 1 and 2.
const a1 = [1, 2, 3, 4, 5];
// Remove elements at index 1 and 2
const a2 = a1.filter(
(_, index) => index !== 1 && index !== 2
);
console.log(a2);
console.log(a1);
Output
[ 1, 4, 5 ] [ 1, 2, 3, 4, 5 ]
Approach 3: Using Spread Operator (...) and slice()
The spread operator (...) can combine multiple portions of an array into a new array. By using it with slice(), specific elements can be excluded without mutating the original array.
Example: Remove the elements at indexes 1 and 2 using slice() and the spread operator.
const a1 = [1, 2, 3, 4, 5];
// Remove elements at index 1 and 2
const a2 = [
...a1.slice(0, 1),
...a1.slice(3)
];
console.log(a2);
console.log(a1);
Output
[ 1, 4, 5 ] [ 1, 2, 3, 4, 5 ]
Approach 4: Using map() and filter()
The map() method can be combined with filter() when removal involves more complex conditions. However, for simply removing elements, filter() alone is generally more suitable.
Example: Mark the elements at indexes 1 and 2 for removal and then filter them out.
const a1 = [1, 2, 3, 4, 5];
// Remove elements at index 1 and 2
const a2 = a1
.map((el, index) =>
index === 1 || index === 2 ? null : el
)
.filter(el => el !== null);
console.log(a2);
console.log(a1);
Output
[ 1, 4, 5 ] [ 1, 2, 3, 4, 5 ]