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:
// ONLINE-RUNNER:browser;
const array = ['a', 'b', 'c', 'd'];
var replacements = ['x', 'y'];
var n = replacements.length; // number of items to replace
array.splice(-n, n);
for (var i = 0; i < n; ++i) {
array.push(replacements[i]);
}
console.log(array); // ['a', 'b', 'x', 'y']
or:
// ONLINE-RUNNER:browser;
let array = ['a', 'b', 'c', 'd'];
let replacements = ['x', 'y'];
const n = replacements.length; // number of items to replace
array.splice(-n, n);
array = [...array, ...replacements];
console.log(array); // ['a', 'b', 'x', 'y']
Reusable arrow function
In this example, we create a reusable arrow function (modern JavaScript syntax) that can be used to replace n items in array.
Example 1
// ONLINE-RUNNER:browser;
const replaceItems = (array, replacements) => {
const n = replacements.length; // number of items to replace
array.splice(-n, n);
for (let i = 0; i < n; ++i) {
array.push(replacements[i]);
}
return array;
};
// Usage example:
const array = ['a', 'b', 'c', 'd'];
const replacements = ['x', 'y'];
replaceItems(array, replacements);
console.log(array); // ['a', 'b', 'x', 'y']
Example 2
// ONLINE-RUNNER:browser;
const replaceItems = (array, replacements) => {
const n = replacements.length; // number of items to replace
array.splice(-n, n);
return [...array, ...replacements];
};
// Usage example:
const array = ['a', 'b', 'c', 'd'];
const replacements = ['x', 'y'];
const result = replaceItems(array, replacements);
console.log(result); // ['a', 'b', 'x', 'y']