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



7 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. I appreciate your efforts because it conveys the message of what you are trying to say. It's a great skill to make even the person who doesn't know about the subject could able to understand the subject . Your blogs are understandable and also elaborately described.

    rpa training in bangalore
    best rpa training in bangalore
    RPA training in bangalore
    RPA courses in bangalore

    ReplyDelete
  3. This is an awesome post.Really very informative and creative contents. These concept is a good way to enhance the knowledge.
    I like it and help me to development very well.Thank you for this brief explanation and very nice information.Well, got a good knowledge.
    Java training in Chennai
    Java training in Bangalore
    Java online training
    Java training in Pune






    ReplyDelete
  4. Hmm, it seems like your site ate my first comment (it was extremely long) so I guess I’ll just sum it up what I had written and say, I’m thoroughly enjoying your blog. I as well as an aspiring blog writer, but I’m still new to the whole thing. Do you have any recommendations for newbie blog writers? I’d appreciate it.
    AWS Course Interview Questions and Answers for Freshers | AWS Interviews Questions and Answers for Devops
    AWS Interview questions and answers for Sysops |AWS Interview Question and Answers BlogSpot

    ReplyDelete
  5. Your good knowledge and kindness in playing with all the pieces were very useful. I don’t know what I would have done if I had not encountered such a step like this.
    AWS Training in Bangalore

    ReplyDelete