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