How can we concatenate arrays in javascript?

Arrays are an important data structure in javascript. An array is an ordered collection of elements that can be accessed by its index value. When working with arrays, one important operation we might need to carry out is that of concatenating arrays.

When we need to concatenate arrays in javascript, the order of combining the arrays matters. If we use + to denote array concatenation, then array1 + array2 and array2 + array1 will produce two different results.

The following sections will discuss three different methods of concatenating arrays in javascript. Some of the methods leave the original arrays unchanged, while one method modifies an array to get the desired result.

Immutable Concatenation of arrays in JS

The following methods can be used to combine two, or more, arrays without modifying the original arrays.

Use the spread operator to concatenate arrays in javascript

The spread operator ‘unpacks’ the elements of an array so that javascript can ‘pack’ them into another array. We can make use of this feature of javascript to combine two or more arrays into one array. For example, to use the spread operator to combine four arrays, array1, array2, array3, array4, we do the following;


let mergeResult = [...array1, ...array2, ...array3, ...array4];

In the next example, we want to combine, or concatenate two arrays; one containing even numbers, and another with prime numbers.


// Define the arrays we want to concatenate
let even_nums = [2, 4, 6, 8];
let prime_nums = [2, 3, 5, 7, 11];

// concatenate primes after evens
console.log('even_nums + prime_nums: ', [...even_nums, ...prime_nums]);

// concatenate evens after primes
console.log('prime_nums + even_nums: ', [...prime_nums, ...even_nums]);

// display the original arrays
console.log('original arrays:');
console.log('even_nums: ', even_nums);
console.log('prime_nums: ', prime_nums);

The result of running the above code is shown in the output below;

Output:


even_nums + prime_nums:  [2, 4, 6, 8, 2, 3, 5, 7, 11]
prime_nums + even_nums:  [2, 3, 5, 7, 11, 2, 4, 6, 8]
original arrays:
even_nums:  [ 2, 4, 6, 8 ]
prime_nums:  [ 2, 3, 5, 7, 11 ]

The concatenation was successful using the spread operator. Using the spread operator, the original arrays remain unchanged after the concatenation has been completed. So, using the spread operator allows us to do an immutable concatenation of two arrays.

Using array.concat() function to concatenate arrays

Another way to concatenate two arrays in javascript without mutating any of the arrays is by using the array.concat() method. array.concat() returns a new array having the merged result. There are two ways we can carry out the concatenation using array.concat();

Either call concat() on the first array;


let mergeResult = array1.concat(array2);

Or, call concat() on an empty array, passing the two arrays as arguments to concat();


let mergeResult = [].concat(array1, array2);

From the second form, we see that concat() can accept more than one array as an argument. We will illustrate the use of array.concat() to concatenate arrays with an example.


// define three arrays to hold different kinds of animals
let fishes = ['sardine', 'trout', 'herring'];
let reptiles = ['crocodile', 'turtle', 'aligator', 'lizard'];
let mammals = ['dog', 'lion', 'wolf', 'elephant', 'bison'];

// concatenate all three arrays
console.log('mammals + reptiles + fishes:');
console.log(mammals.concat(reptiles).concat(fishes));

// print out the original arrays
console.log('fishes: ', fishes);
console.log('reptiles: ', reptiles);
console.log('mammals: ', mammals);


In this example, we defined three arrays, each holding a different class of animals. Then, we used array.concat() to combine the three arrays into one without mutating any of the arrays. We see this in the output below;

Output:


mammals + reptiles + fishes:
[
  'dog',    'lion',
  'wolf',   'elephant',
  'bison',  'crocodile',
  'turtle', 'aligator',
  'lizard', 'sardine',
  'trout',  'herring'
]
fishes:  [ 'sardine', 'trout', 'herring' ]
reptiles:  [ 'crocodile', 'turtle', 'aligator', 'lizard' ]
mammals:  [ 'dog', 'lion', 'wolf', 'elephant', 'bison' ]

Its now time to see how to concatenate arrays in a mutable way.

Mutable Array concatenation in JavaScript

When we used the spread operator and array.concat() to combine two arrays, none of the arrays were modified. There is still one more way to combine arrays in javascript; by making use of array.push(). The primary use of array.push() method is to append elements to the end of an array. We can still make use of array.push() to combine two arrays.

The syntax of array.push() is:

array.push(item1, item2, ..., itemN)

In other words, the method array.push() takes one or more items we want to append to the end of the existing array. So, how do we make use of push to combine two arrays? Consider the following example where we want to combine an array of metals with an array of non-metals;


// define the two arrays we want to combine
let metals = ['lithium', 'cobalt', 'nickel', 'sodium'];
let non_metals = ['iodine', 'carbon', 'silicon', 'nitrogen', 'sulphur'];

// use push() mehod
metals.push(non_metals);

// display the arrays
console.log('new metals array: ', metals);
console.log('non_metals array: ', non_metals);

When we execute the code, we get the following output;

Output:


new metals array:  [
  'lithium',
  'cobalt',
  'nickel',
  'sodium',
  [ 'iodine', 'carbon', 'silicon', 'nitrogen', 'sulphur' ]
]
non_metals array:  [ 'iodine', 'carbon', 'silicon', 'nitrogen', 'sulphur' ]

metals.push() actually does what it was designed to do; it appends non_metals to the end of metals array. We can see this in the output. But did you notice an issue? Using metals.push(non_metals) doesn’t yield the result we seek; it just appends non_metals array as it was to the metals array. To alleviate this, we can use the spread operator to ‘unpack’ the non_metals array, so that metals.push() appends the items in non_metals to the end of the array metals.


// define the two arrays we want to combine
let metals = ['lithium', 'cobalt', 'nickel', 'sodium'];
let non_metals = ['iodine', 'carbon', 'silicon', 'nitrogen', 'sulphur'];

// use push() method, but unpack the non_metals array using spread operator
metals.push(...non_metals);

// display the arrays
console.log('new metals array: ', metals);
console.log('non_metals array: ', non_metals);

Now, we made use of the spread operator to ‘unpack’ the non_metals array, so that metals.push() gives us the result we are looking for. See the next output for the result.

Output:


new metals array:  [
  'lithium', 'cobalt',
  'nickel',  'sodium',
  'iodine',  'carbon',
  'silicon', 'nitrogen',
  'sulphur'
]
non_metals array:  [ 'iodine', 'carbon', 'silicon', 'nitrogen', 'sulphur' ]

metals has been modified, or mutated, by our attempt to concatenate non_metals to it. If we do not want to modify any of the arrays involved in the concatenation, we can do the following;


// define the two arrays we want to combine
let metals = ['lithium', 'cobalt', 'nickel', 'sodium'];
let non_metals = ['iodine', 'carbon', 'silicon', 'nitrogen', 'sulphur'];

/* define an array, elements, to hold the final result of the 
concatenation. array elements will be mutated as a result of making
use of elements.push() */
elements = [];

// push() metals and non_metals to elements array
elements.push(...metals, ...non_metals);

// display the results
console.log('elements: ', elements);
console.log('metals: ', metals);
console.log('non_metals: ', non_metals);

In this example, we defined a new array variable elements to hold the results of the concatenation of metals and non_metals. As a result, only elements was modified by the call to elements.push(). The variables metals and non_metals remained unmodified. The resulting output is shown below;

Output:


elements:  [
  'lithium', 'cobalt',
  'nickel',  'sodium',
  'iodine',  'carbon',
  'silicon', 'nitrogen',
  'sulphur'
]
metals:  [ 'lithium', 'cobalt', 'nickel', 'sodium' ]
non_metals:  [ 'iodine', 'carbon', 'silicon', 'nitrogen', 'sulphur' ]

Conclusion

That’s it for the tutorial. Now that you’ve made it this far, you can merge, or concatenate arrays in javascript. Check out our other javascript tutorials-

And keep improving your frontend skills!!! Like this article? Follow us on Facebook and LinkedIn.