Languages
[Edit]
EN

JavaScript - replace last n items in array

0 points
Created by:
JoanneSenior
1070

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']

 

See also

  1. JavaScript - replace last item in array

References

  1. Array.prototype.splice() - JavaScript | MDN
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join