I want to extend an existing JavaScript array with another array (emulating Python’s extend method).
I know that concat()
creates a new array, but I’m looking for a way to modify the original array directly. The goal is to avoid copying the entire array if one is significantly larger than the other. Any efficient solution?
Hey! One of the most straightforward ways is using push()
along with the spread operator. So if you have:
let a = [1, 2];
let b = [3, 4, 5];
a.push(...b);
That’ll update a
in place. Just a heads-up though m if b
is really large, spreading it might hit the call stack limit. So it works great for small to moderate arrays, but not ideal if b
has, say, 100,000+ items.
If you’re worried about performance with large arrays, you can go old-school and loop through the second array:
let a = [1, 2];
let b = [3, 4, 5];
for (let i = 0; i < b.length; i++) {
a.push(b[i]);
}
It’s simple, doesn’t risk stack issues, and it modifies a
directly. Works well when you’re handling large datasets.
Another neat option is using forEach()
— a bit more readable than a for
loop for some:
let a = [1, 2];
let b = [3, 4, 5];
b.forEach(item => a.push(item));
It still updates the original array a
and avoids creating a new one. This can be especially nice if you want to insert additional logic while pushing items too.