Combining two arrays in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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 ] ]
raja
Published on 23-Nov-2020 10:42:03
Advertisements