Can we merge two arrays in one array in JavaScript???
Yes, It's definitely possible by concat() array method.
So, Let's start to learn what is concat() array method and how it works.
ā¢ What is Concat() Array
method ?
=> In this method two or more
than two arrays merge into
a single array.
The new array serialized
according to original
arrays.
ā¢ Syntax of Concat() method
array1.concat(array2)
ā¢ Example
ā¢ Explanation :-
(1) In the above example I
simply created two
arrays and name of
arrays are 'arr1' and
'arr2' respectively.
(2) Then I stored some
values in that arrays and
values are [1,2] and
[3,4].
(3) Now I was used cancat()
method to merge both
arrays.
(4) According to above
example I wrote arr1 first
and then used concat()
method and pass as
parameter second array and
the output is [1,2,3,4].
(5) Because doing this it's
return arr1 first then
arr2. If I wrote arr2
first then concat method
used the output is
different. See below code
![example 2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/otzxwn7tdcfjn8c7eeyz.jpg)
(6) Now, you can see the
output different, output
is [3,4,1,2].
ā¢ The concat() methods also take individual as arguments like below.
Happy coding....
š Stay tuned with us for more
JavaScript topics.
š Thanks for reading...
Top comments (2)
SInce ES6, it is also possible to use the spread operator which is arguably more readable:
nice to code but apply spreedOperator with array
const arr1 = [1, 2];
const arr2 = [3, 4];
const arr_concat = [...arr1, ...arr2]; //get array1, array2
console.log(arr_concat) // 1, 2, 3, 4