Categories
JavaScript Answers

How to replace elements in array with elements of another array with JavaScript?

Spread the love

To replace elements in array with elements of another array with JavaScript, we use the splice method.

For instance, we write

const a = [1, 2, 3, 4, 5];
const b = [10, 20, 30];
a.splice(0, b.length, ...b);

to call a.splice with 0, b.length and the elements in b as arguments to replace the items in a between index 0 and b.length - 1 with the items in b in place.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *