Applying a custom function to each corresponding element of two arrays using JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in a callback function (which takes in two arguments and returns a value) as the first argument and two arrays of essentially the same length as the second and third argument.

Our function should construct and return a new array whose each corresponding element is the return value of the callback function if corresponding numbers of the input array are provided to it.

Example

Following is the code −

 Live Demo

const arr1 = [1, 2, 3, 4];
const arr2 = [5, 6, 7, 8];
const add = (a, b) => a + b;
const applyFunction = (callback = () => {}, arr1 = [], arr2 = []) => {
   const res = [];
   arr1.forEach((num1, ind) => {
      const num2 = arr2[ind];
      res.push(callback(num1, num2));
   });
   return res;
};
console.log(applyFunction(add, arr1, arr2));

Output

[6, 8, 10, 12]
raja
Published on 20-Apr-2021 09:17:43
Advertisements