Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dividing elements in one array by elements in other?

Tags:

javascript

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]

like image 541
Legend Avatar asked Mar 13 '12 05:03

Legend


2 Answers

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.

like image 193
otakustay Avatar answered Sep 22 '22 10:09

otakustay


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]);
}
like image 45
Waynn Lue Avatar answered Sep 22 '22 10:09

Waynn Lue