
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
Joining two Arrays in Javascript
There are two ways to join 2 arrays in Javascript. If you want to get a new array and not want to disturb the existing arrays while joining the two arrays then you should use the concat method as follows −
Example
let arr1 = [1, 2, 3, 4]; let arr2 = [5, 6, 7, 8]; let arr3 = arr1.concat(arr2); console.log(arr1); console.log(arr2); console.log(arr3);
Output
This will give the output −
[1, 2, 3, 4] [5, 6, 7, 8] [1, 2, 3, 4, 5, 6, 7, 8]
Note that the existing arrays were not modified. If you want to join in place, you'll need to use the push method with apply. The apply function unpacks values from an array and passes it to the function it is applied to as arguments. For example,
Example
let arr1 = [1, 2, 3, 4]; let arr2 = [5, 6, 7, 8]; arr1.push.apply(arr2); console.log(arr1); console.log(arr2);
Output
This will give the output −
[1, 2, 3, 4, 5, 6, 7, 8] [5, 6, 7, 8]
Note that here the first array was changed itself.
- Related Articles
- Joining two hash tables in Javascript
- Deviations in two JavaScript arrays in JavaScript
- Combining two arrays in JavaScript
- Balancing two arrays in JavaScript
- Combine two different arrays in JavaScript
- isSubset of two arrays in JavaScript
- Construct objects from joining two strings JavaScript
- Alternatively merging two arrays - JavaScript
- Equality of two arrays JavaScript
- Intersection of two arrays JavaScript
- How to merge two arrays in JavaScript?
- Reverse sum of two arrays in JavaScript
- Sorting arrays by two criteria in JavaScript
- How to join two arrays in JavaScript?
- How to multiply two Arrays in JavaScript?

Advertisements