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:
// ONLINE-RUNNER:browser;
var array = [1, 2, 3, 4];
var index = 1;
var result = array.filter((value, i) => i !== index);
console.log(result); // [ 1, 3, 4 ]
Reusable function example
In this example, we create a reusable function that creates a copy of a given array with an item removed by the index.
// ONLINE-RUNNER:browser;
function removeItem(array, index) {
return array.filter((value, i) => i !== index);
}
// Usage example:
var array = [1, 2, 3, 4];
var copy1 = removeItem(array, 0);
var copy2 = removeItem(array, 1);
var copy3 = removeItem(array, 2);
console.log(copy1); // [ 2, 3, 4 ]
console.log(copy2); // [ 1, 3, 4 ]
console.log(copy3); // [ 1, 2, 4 ]