How to merge arrays in JavaScript
Today we’ll explain to you how to merge arrays in JavaScript. Here we show you multiple ways to merge two or more arrays and return a new combined array.
Ways to merge arrays in JavaScript
1. concat() method
It’s a simple JavaScript method to combine two or more arrays. This method merge the arrays and returns the new array.
Let’s take an example, suppose we have two arrays like below.
1 2 3 4 5 6 7 8 9 | var array1 = [1, 5, 7, 8, “abc”]; var array2 = [2, 4, 6, 9, ”xyz”]; var combinedArray = array1.concat(array2); // OR var combinedArray = [].concat(array1, array2); console.log(combinedArray); // Output: [1, 5, 7, 8, "abc", 2, 4, 6, 9, "xyz"] |
2. Spread operator
Spread operator is introduced by JavaScript ES6. Spread operator also concatenates the array values and returns the new array.
1 2 3 4 5 | var array1 = [1, 5, 7, 8, “abc”]; var array2 = [2, 4, 6, 9, “xyz”]; var combinedArray = [...array1, ...array2]; console.log(combinedArray); // Output: [1, 5, 7, 8, "abc", 2, 4, 6, 9, "xyz"] |
3. push() method
Using push() method, you can merge the multiple arrays as below.
1 2 3 4 5 6 7 8 9 | var array1 = [1, 5, 7, ”abc”]; var array2 = [2, 4, 6, “pqr”]; var array3 = [3, 8, 9, ”xyz”]; var combinedArray = []; combinedArray.push(...array1, ...array2, ...array3); console.log(combinedArray); // Output: [1, 5, 7, "abc", 2, 4, 6, "pqr", 3, 8, 9, "xyz"] |
Here, we use the push()
method with spread operator to add the elements of the all arrays into a defined combinedArray
array.
If you don’t use spread operator then the whole array will be pushed into a defined array like below.
1 2 3 4 5 6 7 8 9 10 11 12 | var array1 = [1, 5, 7, ”abc”]; var array2 = [2, 4, 6, ”pqr”]; var array3 = [3, 8, 9, “xyz”]; var combinedArray = []; combinedArray.push(array1, array2, array3); console.log(combinedArray); // Output: [ [1, 5, 7, 'abc'], [2, 4, 6, 'pqr'], [3, 8, 9, 'xyz'] ] |
That’s it for today.
Thank you for reading. Happy Coding..!!