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:

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

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

but the trick is doing:
>>> [1, 2, 3, 4, 5, 6] // where a is [1, 2, 3, 4, 5, 6]

(*)To understand how apply works:


  1. You probably meant "a.push.apply(a, b)". You may link some page that explains how it works, in fact it's pretty straightforward:

  2. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Front end developer learn from Javascript Training in Chennai . or Javascript Training in Chennai. Nowadays JavaScript has tons of job opportunities on various vertical industry. ES6 Training in Chennai