If you want to merge two or more arrays into a single array, use the JavaScript array concat() method.
The concat() method does not modify the existing arrays and returns the new array, which is a merger of two or more arrays.
You can pass one or more arrays to the concat() method.
let primeNumbers = [2, 3, 5, 7, 11]; let compositeNumbers = [9, 15, 4, 51]; let primeAndComposite = primeNumbers.concat(compositeNumbers); console.log(primeAndComposite);
Output
[2, 3, 5, 7, 11, 9, 15, 4, 51]
You can also merge arrays using an empty array like the one shown below:
let primeNumbers = [2, 3, 5, 7, 11]; let compositeNumbers = [9, 15, 4, 51]; let primeAndComposite = [].concat(primeNumbers, compositeNumbers); console.log(primeAndComposite);
If you update the existing arrays after calling the concat() method, the newly created array by the concat() method will remain unaffected.
primeNumbers[1] = 13; compositeNumbers[0] = 126; console.log(primeAndComposite); //[2, 3, 5, 7, 11, 9, 15, 4, 51]
You can also merge more than two arrays in JavaScript using the same concat() method. All you have to do is pass multiple arrays to the concat() method.
let dcComics = ['Batman', 'Superman', 'Wonder Woman']; let marvels = ['Spiderman', 'Thor', 'Iron Man', 'Captain America']; let xmen = ['Wolverine', 'Professor X']; let superheroes = xmen.concat(dcComics, marvels); console.log(superheroes);
Output
["Wolverine", "Professor X", "Batman", "Superman", "Wonder Woman", "Spiderman", "Thor", "Iron Man", "Captain America"]
There are no hard and fast rules to pass a one-dimensional array to the concat() method. You are allowed to pass a 2-dimensional and even higher dimensional array to the concat() method.
let arr1 = [[1, 2, 3], [4, 5, 6]]; let arr2 = [7, 8, [9, 10]]; let arr = arr1.concat(arr2); console.log(arr);
Output
[[1, 2, 3], [4, 5, 6], 7, 8, [9, 10]]
ES6 provides a spread operator that enables you to merge arrays without using the concat() method. Let's merge arrays using the spread operator.
let primeNumbers = [2, 3, 5, 7, 11]; let compositeNumbers = [9, 15, 4, 51]; let primeAndComposite = [...primeNumbers, ...compositeNumbers]; console.log(primeAndComposite);
Output
[2, 3, 5, 7, 11, 9, 15, 4, 51]