Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Applying a custom function to each corresponding element of two arrays using JavaScript
We need to write a JavaScript function that applies a custom callback function to corresponding elements of two arrays, creating a new array with the results.
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 ?
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));
[ 6, 8, 10, 12 ]
Using Different Callback Functions
const arr1 = [10, 20, 30];
const arr2 = [2, 4, 6];
// Different operations
const multiply = (a, b) => a * b;
const subtract = (a, b) => a - b;
const divide = (a, b) => a / b;
console.log("Multiplication:", applyFunction(multiply, arr1, arr2));
console.log("Subtraction:", applyFunction(subtract, arr1, arr2));
console.log("Division:", applyFunction(divide, arr1, arr2));
Multiplication: [ 20, 80, 180 ] Subtraction: [ 8, 16, 24 ] Division: [ 5, 5, 5 ]
Alternative Implementation Using map()
const applyFunctionMap = (callback, arr1, arr2) => {
return arr1.map((val, index) => callback(val, arr2[index]));
};
const numbers1 = [3, 7, 11];
const numbers2 = [2, 3, 4];
const power = (base, exp) => Math.pow(base, exp);
console.log("Using map():", applyFunctionMap(power, numbers1, numbers2));
Using map(): [ 9, 343, 14641 ]
How It Works
The function iterates through the first array using forEach() and for each element at index i, it takes the corresponding element from the second array at the same index. These two values are passed to the callback function, and the result is pushed to a new array.
Conclusion
This pattern allows you to apply any custom operation to corresponding elements of two arrays. You can use either forEach() with manual array building or map() for a more functional approach.
