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