Concat or merge array of objects in javaScript; Through this tutorial, i am going to show you how to concate or merge or combine two or more arrays in javascript with examples.
Using the concat() method, you can merge or combine or concat two or more array in javaScript.
JavaScript Concat or Merge Array
- JavaScript Concat() Method
- Syntax of the JavaScript Concat or Merge Array
- Parameters of the javaScript concat() method
- Example 1 – JavaScript Concat 2 Array
- Example 2 – Concat 3 Array in JavaScript
- Example 3 – javaScript Concat Array using For Loop
- Example 4 – Merge Array Using the Spread operator
JavaScript Concat() Method
Array concat() method is pre build javascript method, which is commonly used to combine or concatenate or merge two or more arrays in javaScript.
Note: This method merges or adds two or more arrays and returns a new single array.
Syntax of the JavaScript Concat or Merge Array
The basic syntax of javascript concat() method is following:
array.concat(array_second, array_third, …, array_n);
Parameters of the javaScript concat() method
Parameter | Description |
---|---|
array_one, array_two,….. array_n | This is required. The arrays to be merged |
Example 1 – JavaScript Concat 2 Array
Here, i will take simple example using javaScript concat() method to merge two array in javascript; as shown below:
var array = ["php", "java"]; var array2 = ["c", "c#", ".net"]; var res = array.concat(array2); console.log(res);
The output of the above code is: (5) [“php”, “java”, “c”, “c#”, “.net”]
Example 2 – Concat 3 Array in JavaScript
Here, i will take second example for merge or combine 3 javascript numeric arrays; as shown below:
var array = [1,2,3]; var array2 = [4,5,6]; var array3 = [7,8,9,10]; var res = array.concat(array2, array3); console.log(res);
The output of the above code is: (10) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Example 3 – javaScript Concat Array using For Loop
Using for loop to merge or combine arrays; as shown below:
const merge = (first, second) => { for(let i=0; i<second.length; i++) { first.push(second[i]); } return first; } merge([1,2,3], [4,5,6]);
The output of the above code is: (6) [1, 2, 3, 4, 5, 6,]
Example 4 – Merge Array Using the Spread operator
Using spread operator to merge or combine arrays; as shown below:
const arr1 = [1,2,3]; const arr2 = [4,5,6]; // Merge arrays const merged = [...arr1, ...arr2]; console.log(merged); // [1,2,3,4,5,6] console.log(arr1); // [1,2,3] console.log(arr2); // [4,5,6]
The output of the above code is: (6) [1, 2, 3, 4, 5, 6,]
Conclusion
In this tutorial, you have learned how to merge two or more arrays together in javascript using the array concat() method of javascript.