ПІДТРИМАЙ УКРАЇНУ ПІДТРИМАТИ АРМІЮ
Uk Uk

How to Concatenate Arrays in JavaScript: A Comprehensive Guide

How to Concatenate Arrays in JavaScript: A Comprehensive Guide

Learn various methods to merge arrays in JavaScript, including the concat() method and alternative techniques, with practical example

What is concat method?

Concat is used to merge two or more arrays and it always returns a new array instead of modifying the original arrays.

Example - 1

const array1 = [1,2,3,4,5,6];
const array2 = ["A","B","C","D"];

const array1ToArray2 = array1.concat(array2)
const array2ToArray1 = array2.concat(array1)

console.log(array1ToArray2)
console.log(array2ToArray1)

Output -

[
 1, 2, 3, 4, 5,
 6, 'A', 'B', 'C', 'D'
]
[
 'A', 'B', 'C', 'D', 1,
 2, 3, 4, 5, 6
]
  • As you can see we have merged two arrays, one in which we have merged array1 to array2 and second in which we have merged array2 in array1.

Example 2 -

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

const array1To2dArray = array1.concat(array2d)

console.log(array1To2dArray);

Output -

[ 1, 2, 3, 4, 5, 6, [ 1, 2 ], [ 3, 4 ], [ [ 5, 6 ], [ 7, 8 ] ] ]
  • We have merged array1 with a 2-d array.

Example 3 -

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

const separateConcatening = array1.concat(7,8,9,"E","F",true,false,null,undefined,
[10,11,"G","H"],{name:"shubham",age:21},12.967)

console.log(separateConcatening)

Output-

[1,2,3,4,5,6,7,8,9,'E','F',true,false,null,undefined,
 10,11,'G','H',{ name: 'shubham', age: 21 },12.967
]
  • Here we have concated array1 with seprate items of different data type like strings, numbers float, boolean,null,undefined,array,object.

Example - 4

const array1 = [1,2,3,4,5,6];
const array2 = ["A","B","C","D"];
const array2d = [[1,2],[3,4],[[5,6],[7,8]]];

const concatArray = (...args) => {
 return args.flat(Infinity)
}

console.log(concatArray([1,2,3,4],[5,6,7,8],array1,array2,array2d))

Output -

[
 1, 2, 3, 4, 5, 6, 7, 8,
 1, 2, 3, 4, 5, 6, 'A', 'B',
 'C', 'D', 1, 2, 3, 4, 5, 6,
 7, 8
]
  • We have created an arrow function which accepts an argument as rest parameter so that we can pass any number of arrays to it.
  • Then using the array flat() method we have flatten the those array which are 2-dimensional and the returned result will be a 1-d array.

Example - 5

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

const array1ToArray1 = array1.concat(array1)

console.log(array1ToArray1)

Output -

[
 1, 2, 3, 4, 5,
 6, 1, 2, 3, 4,
 5, 6
]
  • Here we have merged array1 with itself.

Example - 6

const array1 = [1,2,3,4,5,6];
const array2 = ["A","B","C","D"];
const array2d = [[1,2],[3,4],[[5,6],[7,8]]];

const array1ToMultiple = array1.concat(array1,array2,array2d)
console.log(array1ToMultiple)

Output -

[1,2,3,4,5,6,1,2,3,4,5,6,'A', 'B', 'C', 'D',[ 1, 2 ],
 [ 3, 4 ],
 [ [ 5, 6 ], [ 7, 8 ] ]]

We can also merge multiple arrays by passing them inside concat method.

Ресурс : dev.to


Scroll to Top