Sunday 22 May 2011

Appending to an array

JavaScript's Array#concat function is handy and cool, but it creates a copy of both arrays. That is, given array a and array b, a.concat(b) will create a third array c with the contents of both of them, leaving a and b intact. Now, sometimes that's what you want, but other times you just want to append b to a without creating a copy of a.

While JavaScript doesn't have a dedicated append function, there's a surprisingly efficient and concise way to do it:

a.push.apply(a, b);

That calls the push method via apply, which accepts a context argument (what the this value should be during the call) and any array-like object providing the arguments to give the call. Since push allows you to push multiple elements with a single call, that works a treat. And somewhat unusually for JavaScript, it's probably the most efficient way to do it on all platforms (where normally this sort of thing is faster on some and slower on others)

Now, if you do this in code other people are going to have to read, I'd recommend a comment saying "Appends `b` to `a` in place" or some such, because otherwise it's pretty opaque to people who don't know JavaScript well. Or, of course you could always add an append method to arrays:

(function() {
var push = Array.prototype.push;

function Array_append(array) {
push.apply(this, array);
return this;
}

if (Object.defineProperty) {
Object.defineProperty(Array.prototype, "append", {
enumerable: false,
value: Array_append
});
}
else {
Array.prototype.append = Array_append;
}
})();

As always, if you're doing that on platforms that don't have Object.defineProperty (and there are still a lot in the wild), make sure you don't have any broken for..in loops lying around.

No comments: