EN
JavaScript - replace many elements in array
12
points
In JavaScript, it is not intuitive to replace many elements in the array. Replace operation can be achieved with Array.prototype.splice
method. This article is focused on how to do it.
1. Replace many elements with Array.prototype.splice
method example
// index: 0 1 2 3 4 5 6
var array = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
// removing 4 elements sice 1st index position
// inserting sice 1st index position 4 elements
array.splice(1, 4, 'new item 1', 'new item 2', 'new item 3', 'new item N');
console.log(array);
Output:
[
'a',
'new item 1',
'new item 2',
'new item 3',
'new item N',
'f',
'g'
]
Notes about
Array.prototype.splice
method:
- takes as first argument index of begining of removed elements
- takes as second argument number of removed elements
- takes as third and next arguments added elements