loading...

Understanding JavaScript Array Series XVII - Array.concat()

nedyudombat profile image Nedy Udombat ・2 min read

Concatenate literally means putting things together in a chain or series. So if we want to merge two arrays together, one way of doing it would be to concatenate it.

How do we concatenate two arrays?

We can achieve this by using the Array.concat() array method in javascript. This method merges two arrays into a new array. It takes array1 & array2 and merges them into array3.

Here is an example:

const array1 = [1, 2, 3, 4, 5];
const array2 = [6, 7, 8, 9];

const array3 = array1.concat(array2);
console.log(array3); // [1, 2, 3, 4, 5, 6, 7, 8, 9]

From the example, above we can see that this method creates a new array, passes in all the values of the first array, then it passes in the value of the second array.

Before we go into more examplesa let's look at the syntax

Thank you for reading. :thumbsup:
const newArray = array1.concat(value1, value2, ..., valueX)

[newArray]: This is the new array instance that is created as a result of the concatenation.

[array1]: This is the array which other arrays will be concatenated to.

[value1, value2, ..., valueX]: This is the value to be concatenated to array1. This value could also be other data types too like string, integer etc. If this value is not provided to the method, the method returns a shallow copy of array1.

N/B: For the primitive data types (string, integer, boolean ...), the array.concat() copies the value into the new array, but for some non-primitive data types (array, object ...), it copies the object reference into the newArray.

More Examples:

Can you merge two arrays?

const array1 = [1, 2, 3, 4, 5];
const array2 = ["a", "b", "c", "d"];

const array3 = array1.concat(array2);
console.log(array3); // [1, 2, 3, 4, 5, "a", "b", "c", "d"];

How about merging 3 arrays?

const array1 = [1, 2, 3, 4];
const array2 = ["a", "b", "c", "d"];
const array3 = [true, false, null, undefined];

const array4 = array1.concat(array2, array3);
console.log(array4); // [1, 2, 3, 4, "a", "b", "c", "d", true, false, null, undefined]

In this example, the concat() method merges the first array, then it merges the next one until there is has exhausted all the values provided.

What if we want to merge a string and a number into an array?

const array1 = [1, 2, 3, 4, 5];

const array2 = array1.concat("s", 4);
console.log(array2); // [1, 2, 3, 4, 5, "s", 4];

That's all for today, See you next time!!! 😆 😁

Here is the link to the other articles on this Array series written by me:

Got any question, addition or correction? Please leave a comment.

Thank you for reading. 👍

Discussion

pic
Editor guide