Reputation: 116950
Maybe trivial but what is an elegant way of dividing elements in one array by another (assume arrays are of equal length)? For instance
var A = [2,6,12,18]
var B = [2,3,4,6]
Dividing should give me: [1,2,3,3]
Upvotes: 9
Views: 7290
Reputation: 338326
If you consider changing the Array prototype an option:
Array.prototype.zip = function (other, reduce, thisArg) {
var i, result = [], args,
isfunc = typeof reduce == "function",
l = Math.max(this.length, other.length);
for (i=0; i<l; i++) {
args = [ this[i], other[i] ];
result.push( isfunc ? reduce.apply(thisArg, args) : args );
}
return result;
}
var A = [2,6,12,18]
var B = [2,3,4,6]
var C = A.zip(B, function (l, r) { return l / r; });
// -> [1, 2, 3, 3]
Upvotes: 2
Reputation: 16198
There isn't any elegant method per se, as in one which avoids a forloop with a neat trick. There are some methods using map()
which have already been listed. Those end up using a (longer) forloop, but they're smaller pieces of code. Otherwise, use this:
var C= new Array(A.length)
for(i=0;i<A.length;i++){
C[i]=A[i]/B[i];
}
Upvotes: 2
Reputation: 12405
If you have ES5 support, this may be a good option:
var result = A.map(function(n, i) { return n / B[i]; });
Where n
in callback represents the iterated number in A
and i
is the index of n
in A
.
Upvotes: 27
Reputation: 11385
Assuming the two arrays are always the same length:
var C = [];
for (var i = 0; i < A.length; i++) {
C.push(A[i] / B[i]);
}
Upvotes: 3