EN
JavaScript - replace elements in array with elements of another array
1 answers
0 points
How can I replace elements in array with elements of another array?
For example, I have two arrays:
xxxxxxxxxx
1
var array1 = [1, 2, 3, 4, 5];
2
var array2 = ['a', 'b', 'c'];
I want to replace all the elements from index 0
in array1
with the elements of array2
.
The result should be:
xxxxxxxxxx
1
[ 'a', 'b', 'c', 4, 5 ]
How can I do that?
1 answer
0 points
You can use splice()
method to do so.
Practical example
xxxxxxxxxx
1
var array1 = [1, 2, 3, 4, 5];
2
var array2 = ['a', 'b', 'c'];
3
4
Array.prototype.splice.apply(array1, [0, array2.length].concat(array2));
5
6
console.log(array1); // [ 'a', 'b', 'c', 4, 5 ]
See also
References
0 commentsShow commentsAdd comment