
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Combine Two Arrays in JavaScript
We are required to write a JavaScript function that takes in two arrays of the same length.
Our function should then combine corresponding elements of the arrays, to form the corresponding subarray of the output array, and then finally return the output array.
If the two arrays are −
const arr1 = ['a', 'b', 'c']; const arr2 = [1, 2, 3];
Then the output should be −
const output = [ ['a', 1], ['b', 2], ['c', 3] ];
Example
The code for this will be −
const arr1 = ['a', 'b', 'c']; const arr2 = [1, 2, 3]; const combineCorresponding = (arr1 = [], arr2 = []) => { const res = []; for(let i = 0; i < arr1.length; i++){ const el1 = arr1[i]; const el2 = arr2[i]; res.push([el1, el2]); }; return res; }; console.log(combineCorresponding(arr1, arr2));
Output
And the output in the console will be −
[ [ 'a', 1 ], [ 'b', 2 ], [ 'c', 3 ] ]
Advertisements