Thursday, October 13, 2011

Concat in place for Javascript arrays

This one is like black magic.
Javascript Array's concat method creates a new array with the concatenation of 2 arrays. However doing so in place is what you need most of the time:

being:
var a = [1,2,3] , b = [4,5,6];

Push does not work, since it works with  individual elements
a.push(b);
>>> [1, 2, 3, [4, 5, 6]
a try with 'concat' wont work:
a.concat(b)
>>> [1, 2, 3, 4, 5, 6] //returns a new array, where (a is still [1,2,3] )

but the trick is doing:
a.push.apply(a,b);
>>> [1, 2, 3, 4, 5, 6] // where a is [1, 2, 3, 4, 5, 6]




(*)To understand how apply works: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/apply http://trephine.org/t/index.php?title=JavaScript_call_and_apply