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



3 comments:

  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: http://www.sitepoint.com/whats-the-difference-between-function-call-and-function-apply/

    ReplyDelete
  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

    ReplyDelete