How to extend an existing JavaScript array with another array, without creating a new array
Use push
method in combination with the spread operator (...
) to merge arrays "in-place":
More in-depth: Overcoming limitations and handling edge cases
Bypassing spread operator limitations
The spread operator is ideal for simple cases. But with large arrays, you risk the proverbial "train out of the tracks" (i.e., stack overflow error). There's a simple for
loop to the rescue:
Chunking large arrays - no stack overflow!
Really large arrays too much for JavaScript to handle? Piece of cake! Chunk b
into bite-sized pieces and use the push
method in small, digestible iterations:
Back to the ES5 future
In environments where ES6 is a distant dream, the apply
method has your back. It allows applying push
with an array of elements:
Remember though, like the spread operator, this method can also exaggerate a peaky stack height (i.e., cause stack overflow errors with large arrays).
Train connection made easy with JavaScript
Imagine the arrays like two trains on the same track:
Connecting Train B
to Train A
without causing a derailment:
The Result will be a super express!
Here, the 📦s are the array
elements; Train A and Train B melted into a single, powerful locomotive without any major accidents.
Extra tips for efficient JavaScripting
Taking into account performance
Performance depends on size. If a
is significantly larger than b
, go for in-place updates which are much more efficient than creating a new array from scratch.
Do not meddle with core JavaScript objects
We could add a direct extend
method to Array.prototype
(like Python) but putting fingers into JavaScript's fundamental objects will only spell trouble. It's tempting but remember: with great power comes great responsibility. 🕷️
Using forEach with caution
forEach
can help navigate through arrays, even sparse ones. But, doing array.forEach(this.push, this)
might confuse the JavaScript engine about the this
context and unswervingly make a clown out of your code🤡.
When to use concat
concat
makes a new array, should you have an avalanche of array to handle and performance is not your "numero uno" concern. a.concat(b)
gets things done with tiny to moderate size arrays. But remember, using concat
might put a strain on JavaScript's argument limit.
Was this article helpful?