How to append arrays

JavaScript polyfill, by , Friday, March 14th, 2014

If you are simply looking for how to append one array to another, this is really easy in JavaScript. The most straight forward approach is to use the Array.prototype.concat() method. You call it on one array and give the other array as a parameter to the method. It will then return a new array, consisting of the two arrays concatenated.

  1. var numOne = [0, 1, 2, 3, 4],
  2. numTwo = [5, 6, 7, 8, 9],
  3. allNum = numOne.concat(numTwo);
  5. // Prints out [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  6. console.log(allNum);

If you want the concatenated array to be in a specific order, you can apply the Array.prototype.sort() method on it. On how to do that look at either How to sort an array numerically or How to use the Array sort method.

Another way to achieve almost the same result, is by using the Array.prototype.push() method, and call it with the apply method. Unlike the concat method however, this will not return you a new array, but instead will add the elements of the second array to the first.

  1. var numOne = [0, 1, 2, 3, 4],
  2. numTwo = [5, 6, 9, 9, 9];
  4. Array.prototype.push.apply(numOne, numTwo);
  6. // Prints out [0, 1, 2, 3, 4, 5, 6, 9, 9, 9]
  7. console.log(numOne);

The way this works is straight forward; the Array.prototype.push() method is used to push elements into an array on at a time. By calling it with the apply() method we, as the first parameter sets the this value, which is the subject of the operation, and in our case this is the numOne array. Secondly the apply() method allow us to parse an array of parameters, that in turn will be parsed to the method on which it is call on. So in other words; we are calling the array push method repeatedly on the array numOne each time passing it one of the elements in the numTwo array as a parameter, resulting in numOne containing all elements of both arrays.