Separating elements in one array with elements in another?

It may be trivial, but what is an elegant way to divide elements in one array into another (it is assumed that the arrays are of equal length)? For instance,

var A = [2,6,12,18] var B = [2,3,4,6] 

Separation should give me: [1,2,3,3]

+4
source share
4 answers

If you have ES5 support, this might be a good option:

 var result = A.map(function(n, i) { return n / B[i]; }); 

Where n in the callback is an iterated number in A , and i is the index n in A

+13
source

Assuming two arrays always have the same length:

 var C = []; for (var i = 0; i < A.length; i++) { C.push(A[i] / B[i]); } 
+3
source

There is no elegant method as such, as in one that avoids the forlup with a neat trick. There are several methods that have already been listed in map() . They end up using a (longer) forloop, but they are 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]; } 
+2
source

If you decide to change the Array prototype, select the 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] 
+2
source

Source: https://habr.com/ru/post/1401106/


All Articles