JavaScript how to append one array to another

The javascript Array function concat() joins two arrays and returns the new array, so you end up with 3 arrays, the original, the one being appended, and the concatenated array.

This code below extends the array object by adding an append(array) method.  This will append the passed array to the existing array, without creating an intermediate array.

Array.prototype.append = function(a) {
this.push.apply(this,a);
return this;
}

Examples:

[ 0, 1 ].append([ 2, 3 ])
[ 0, 1 ].append([ 2, 3 ]).append([ 4, 5 ])

Note: that this method does not necessarily give the best performance.
http://jsperf.com/array-prototype-push-apply-vs-concat/13

Advertisements

About austinfrance

Technical Developer @ RedSky IT / Explorer Software
This entry was posted in JavaScript. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s