Merge or combine arrays using JavaScript
Today we’ll explain to you how to merge or combine arrays using JavaScript. Here we show you multiple ways to merge two or more arrays and return a new combined array.
- Calculate age using JavaScript
- Generate a random number in given range using JavaScript
- Sort an object array by date in JavaScript
- Validate the value by regular expression in JavaScript
- How to detect the user browser 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.
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.
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.
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.
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..!!