Explain Codes LogoExplain Codes Logo

How to extend an existing JavaScript array with another array, without creating a new array

javascript
array-extensions
performance
best-practices
Nikita BarsukovbyNikita Barsukov·Aug 13, 2024
TLDR

Use push method in combination with the spread operator (...) to merge arrays "in-place":

let existing = [1, 2, 3]; existing.push(...[4, 5, 6]); // adds the new elements right into the "existing" array // existing: [1, 2, 3, 4, 5, 6]

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:

let a = [1, 2, 3], b = [4, 5, 6]; for (let i = 0; i < b.length; i++) { // This loop takes care of each box 📦 at a time a.push(b[i]); } // a: [1, 2, 3, 4, 5, 6]

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:

let chunkSize = 1000; // Size does matter! for (let i = 0; i < b.length; i += chunkSize) { let chunk = b.slice(i, i + chunkSize); a.push(...chunk); // Nom nom nom 🍰 }

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:

Array.prototype.push.apply(a, b); // or a.push.apply(a, b);

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:

Train A (🚂): [📦, 📦, 📦] Train B (🚃): [📦, 📦]

Connecting Train B to Train A without causing a derailment:

TrainA.push.apply(TrainA, TrainB); // TrainA takes all goods of TrainB like a champ!

The Result will be a super express!

Merged Train (🚂🚃): [📦, 📦, 📦, 📦, 📦]

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.

var a = ["huge", "array"], b = ["tiny", "array"]; // If big fish is swallowing the little one 🐟 if (a.length >> b.length) { // Update in-place 🚀 }

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.