having fun with code

Little tricks: concatenating arrays in Javascript

It happens that when working with Javascript frameworks like MooTools for a long time, it’s easy to forget how to do things in plain/native Javascript. For example, concatenating arrays is an easy task thanks to the Function object method apply:

  1. var array1 = [1,2,3,4];
  2. var array2 = [5,6,7];
  3. array1.push.apply(array1, array2); // array1 = [1, 2, 3, 4, 5, 6, 7]
  4. array1.push.apply(array1, [1,2,3]); // array1 = [1, 2, 3, 4, 5, 6, 7, 1, 2, 3]

Note that this method concatenates two arrays, and does not check for duplicate items.

In MooTools, the equivalent to this method would be Array.extend():

  1. var array1 = [1,2,3,4];
  2. var array2 = [5,6,7];
  3. array1.extend(array2); // array1 = [1, 2, 3, 4, 5, 6, 7]
  4. array1.extend([1,2,3]); // array1 = [1, 2, 3, 4, 5, 6, 7, 1, 2, 3]

Again, Array.extend() concatenates two arrays without checking for duplicates.

Related Posts:

4 Comments to Little tricks: concatenating arrays in Javascript

  1. August 12, 2010 at 15:56 | Permalink

    I’ve been using this.

    But your wheel looks nice too. :)

  2. August 18, 2010 at 16:12 | Permalink

    Yup, just depends on which one you’re going for.

Leave a Reply

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Additional comments powered by BackType

About the blog

This is a blog about development, focused mainly on Javascript but also other languages like python, shell scripts and more.

About the author

Eneko Alonso is a software engineer and UI developer with more than eight years of experience in software and web development. He lives in San Luis Obispo, California and works at LEVEL Studios.

Contact Info

Contact Info

PromoteJS

JavaScript JS Documentation