Create functions that will perform the desired operations.
var sum = function(a, b){ return a + b; };
var subtract = function(a, b){ return a - b; };
var multiply = function(a, b){ return a * b; };
var divide = function(a, b){ return a / b; };
This allows for a clear and concise way to manipulate two arrays like so:
var array1 = [1,2,3];
var array2 = [2,4,8];
operateArrays(array1, array2, sum); //[3, 6, 11]
operateArrays(array1, array2, subtract); //[-1, -2, -5]
operateArrays(array1, array2, multiply); //[2, 8, 24]
operateArrays(array1, array2, divide); //[0.5, 0.5, 0.375]
This function is utilized here:
/**
* Divide each number of an array of numbers by another array of numbers
* @param {Array} arrayA The array of numbers
* @param {Array} arrayB The array of numbers
* @param {Function} fn Function that performs an operation
* @return {Array} The resulting array
* @author Victor N. www.vitim.us
*/
function operateArrays(arrayA, arrayB, fn){
if(arrayA.length!==arrayB.length) throw new Error("Cannot operate arrays of different lengths");
return arrayB.map(function(b, i){
return fn(arrayA[i], b);
});
}