EN
JavaScript - replace last n items in array
0 points
In this article, we would like to show you how to replace last n items in array using JavaScript.
Quick solution:
xxxxxxxxxx
1
const array = ['a', 'b', 'c', 'd'];
2
3
var replacements = ['x', 'y'];
4
var n = replacements.length; // number of items to replace
5
6
array.splice(-n, n);
7
8
for (var i = 0; i < n; ++i) {
9
array.push(replacements[i]);
10
}
11
12
console.log(array); // ['a', 'b', 'x', 'y']
or:
xxxxxxxxxx
1
let array = ['a', 'b', 'c', 'd'];
2
let replacements = ['x', 'y'];
3
4
const n = replacements.length; // number of items to replace
5
array.splice(-n, n);
6
array = [array, replacements];
7
8
console.log(array); // ['a', 'b', 'x', 'y']
In this example, we create a reusable arrow function (modern JavaScript syntax) that can be used to replace n items in array
.
xxxxxxxxxx
1
const replaceItems = (array, replacements) => {
2
const n = replacements.length; // number of items to replace
3
array.splice(-n, n);
4
for (let i = 0; i < n; ++i) {
5
array.push(replacements[i]);
6
}
7
return array;
8
};
9
10
11
// Usage example:
12
13
const array = ['a', 'b', 'c', 'd'];
14
const replacements = ['x', 'y'];
15
16
replaceItems(array, replacements);
17
18
console.log(array); // ['a', 'b', 'x', 'y']
xxxxxxxxxx
1
const replaceItems = (array, replacements) => {
2
const n = replacements.length; // number of items to replace
3
array.splice(-n, n);
4
return [array, replacements];
5
};
6
7
8
// Usage example:
9
10
const array = ['a', 'b', 'c', 'd'];
11
const replacements = ['x', 'y'];
12
13
const result = replaceItems(array, replacements);
14
15
console.log(result); // ['a', 'b', 'x', 'y']