JavaScript - Arrays - concat


// JavaScript - Array.prototype.concat
The concat() method is used to merge two or more arrays. This method does not 
change the existing arrays, but instead returns a new array.

var new_array = old_array.concat(value1[, value2[, ...[, valueN]]])

valueN: Arrays and/or values to concatenate into a new array. 

var arr1 = ["a", "b", "c"];
var arr2 = ["d", "e", "f"];
// results in a new array [ "a", "b", "c", "d", "e", "f" ]

The concat method creates a new array consisting of the elements in the object 
on which it is called, followed in order by, for each argument, the elements of 
that argument (if the argument is an array) or the argument itself (if the 
argument is not an array).

The concat method does not alter this or any of the arrays provided as arguments 
but instead returns a shallow copy that contains copies of the same elements 
combined from the original arrays. Elements of the original arrays are copied 
into the new array as follows:

Object references (and not the actual object): concat copies object references 
into the new array. Both the original and new array refer to the same object. 
That is, if a referenced object is modified, the changes are visible to both 
the new and original arrays.

Strings, numbers and booleans (not String, Number, and Boolean objects): concat 
copies the values of strings and numbers into the new array.

Concatenating array(s)/value(s) will leave the originals untouched. Furthermore, 
any operation on the new array(only if the element is not object reference) will 
have no effect on the original arrays, and vice versa.

// Concatenating two arrays:
var alpha = ["a", "b", "c"];
var numeric = [1, 2, 3];
// result in ['a', 'b', 'c', 1, 2, 3]

// Concatenating three arrays:
var num1 = [1, 2, 3],
    num2 = [4, 5, 6],
    num3 = [7, 8, 9];
var nums = num1.concat(num2, num3);

// Concatenating values to an array:
var alpha = ['a', 'b', 'c'];
var alphaNumeric = alpha.concat(1, [2, 3]);
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License