EN
JavaScript - copy array with remove item operation
0 points
In this article, we would like to show you how to copy an array with removed item using JavaScript.
Quick solution:
xxxxxxxxxx
1
var array = [1, 2, 3, 4];
2
var index = 1;
3
4
var result = array.filter((value, i) => i !== index);
5
6
console.log(result); // [ 1, 3, 4 ]
In this example, we create a reusable function that creates a copy of a given array with an item removed by the index.
xxxxxxxxxx
1
function removeItem(array, index) {
2
return array.filter((value, i) => i !== index);
3
}
4
5
6
// Usage example:
7
8
var array = [1, 2, 3, 4];
9
10
var copy1 = removeItem(array, 0);
11
var copy2 = removeItem(array, 1);
12
var copy3 = removeItem(array, 2);
13
14
console.log(copy1); // [ 2, 3, 4 ]
15
console.log(copy2); // [ 1, 3, 4 ]
16
console.log(copy3); // [ 1, 2, 4 ]