📋 Table Of Content
An array is define as an object that represents similar types of elements and can store multiple values at once.
While working with arrays one of the common operation we perform is merging arrays together.
We merge two or more arrays to form one individual array which contains all the elements of the merged arrays.
For example , we merge two array [1,2,3,4] and [7,8,9,10] to form a single array as [1,2,3,4,7,8,9,10].
concat() methods. Let's understand each method with an example.
Using concat() to merge arrays
concat(value0, value1, ... , valueN)
const array1 = [1,2,3,4] const array2 = [7,8,9,10] const merge = .concat(array1, array2) console.log(merge) // output : [1, 2, 3, 4, 7, 8, 9, 10]
OR you can write
Array.concat() method in another way too:
const array1 = [1,2,3,4] const array2 = [7,8,9,10] const merge = array1.concat(array2) console.log(merge) // output : [1, 2, 3, 4, 7, 8, 9, 10]
Array.concat() method do not mutate the array upon which its called but it returns us a new array with all the merged elements.
Using Spread Operator (...)
This is the simplest way to merge arrays together into one big individual array.
The spread Operator (
const array1 = [1,2,3,4] const array2 = [7,8,9,10] const merge = [...array1, ...array2] console.log(merge) // output : [1, 2, 3, 4, 7, 8, 9, 10]
The spread operator (
...) too do not change the original array but creates a new array with merged elements.
Using push() method
We can use this method along with the spread operator(
...) to add the elements of an array to the end of an existing array.
Let's see an example to merge arrays using push() method.
const array1 = [1,2,3,4] const array2 = [7,8,9,10] array1.push(...array2) console.log(array1) // output : [1, 2, 3, 4, 7, 8, 9, 10]
push() method change the array upon which it is merged. Here, in the above example we have merged array2 upon array1.
Which one to use : spread operator or the concat() method?
Even though the spread operator is the modern and the easiest way to merge arrays, you have to make sure that the inputs are all arrays.
For example, if one is a array type and the other is just a string then the merge results would be like:
const array = [1,2,3,4] const str = 'program' const merge = [...array, ...str] console.log(merge) // output : [ 1, 2, 3, 4, 'p', 'r', 'o', 'g', 'r', 'a', 'm' ]
So, if you are unsure about the data type of the element use
const array = [1,2,3,4] const str = 'program' const merge = array.concat(str) console.log(merge) // output : [ 1, 2, 3, 4, 'program' ]