- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
Advertisements