0

Suppose I have two arrays (A and B) which are to be arguments to a function taking two values as arguments (a and b).

How can I use the function and the arrays in such a way that I obtain another array C that stores the result of putting the n-th element of A together with the n-th element of B into the function ...

var A = [1,2,3,4];
var B = [1,2,3,4];

function myFunction(a,b)
{
return a+b ;
}

C than should be something like:

[2,4,6,8]
petermeissner
  • 12,234
  • 5
  • 63
  • 63
  • What would `a` and `b` equal in this example? – tymeJV Nov 13 '13 at 14:09
  • To get the n-th element of an array it's just `myArray[n]`. Here, you could do `A[n]+B[n]`. Put that in a for loop for the length of A/B and iterate n. – Embattled Swag Nov 13 '13 at 14:11
  • @tymeJV : I do not really understand the question ... a and b are the parameters of myFunction, so the values to put in are supposed to be the A[0], B[0] than A[1], B[1] than B[2], B[3] ... is that what you mean? – petermeissner Nov 13 '13 at 14:13
  • I mean given that example, what are `a` and `b`, are they `0,0` `1,0` -- I just don't see what you're doing to get that output – tymeJV Nov 13 '13 at 14:13
  • @tymeJV It's pretty clear. The input is `[1, 2, 3, 4]` and `[1, 2, 3, 4]` and the result should be `[2, 4, 6, 8]` based on that `myFunction` is applied to each pair of the input. – deceze Nov 13 '13 at 14:17
  • @deceze -- I'm an idiot. Was thinking something extremely complicated when it was not :\ -- damnit brain. – tymeJV Nov 13 '13 at 14:20
  • I sum the first element of A and the first element of B than I take the next pair of elements and so on ... it perfectly makes sense in other languages I know. – petermeissner Nov 13 '13 at 14:22

2 Answers2

2

This is commonly knows as "zipWith" and can be implemented like so:

function zipWith(a, b, callback) {
    var c = [];
    for (var i = 0, length = a.length; i < length; i++) {
        // if (typeof b[i] == 'undefined') throw some error or break, your choice
        c.push(callback(a[i], b[i]));
    }
    return c;
}

c = zipWith(A, B, myFunction);
deceze
  • 510,633
  • 85
  • 743
  • 889
  • 1
    [See this related question](http://stackoverflow.com/questions/4856717/javascript-equivalent-of-pythons-zip-function) – p.s.w.g Nov 13 '13 at 14:41
1

You could do it with a simple for-loop:

var C = new Array(A.length);
for (var i = 0; i < A.length; i++)
{
    C[i] = myFunction(A[i], B[i]);
}

Or using the Array.map method (although see ECMAScript 5 compatibility table):

var C = A.map(function(a, i) { return myFunction(a, B[i]); });
p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
  • I realy like usage of map instead of using a loop ... but is'nt there a way to put e.g. A and B together and than map? ... something like: ``var AB = [A,B];`` ``AB.map(myFunction)`` ?? – petermeissner Nov 13 '13 at 14:32
  • 1
    @marvin_dpr Unfortunately no. `map` considers one array, and only one item at a time from that array. – p.s.w.g Nov 13 '13 at 14:39