Samurai Jack
Samurai Jack

Reputation: 3125

Combine two arrays into an array by performing an operation for each pair of values

There are two arrays having same length:

firstArray = [22, 54, 33, 10];
secondArray = [2, 27, 11, 10];

I want to get a third array as result by dividing each element of the first one to its pair in the second one, in this case the result should be:

resultArray = [11, 2, 3, 1];

I tried to do it using foreach() and map() but all I get is undefined values. For example this code:

firstArray.forEach(index) => {
    resultArray[index] = firstArray[index] / secondArray[index];
});

any suggestions?

Upvotes: 1

Views: 74

Answers (4)

Ele
Ele

Reputation: 33726

Using function reduce

var firstArray = [22, 54, 33, 10],
    secondArray = [2, 27, 11, 10],
    thirdArray = firstArray.reduce((a, n, i) => { a[i] = n / secondArray[i]; return a}, []);
    
console.log(thirdArray);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386680

You could map the result of iteration of firstArray and take the value of secondArray with an index.

var firstArray = [22, 54, 33, 10],
    secondArray = [2, 27, 11, 10],
    result = firstArray.map((v , i) => v / secondArray[i]);
    
console.log(result);

Another solution, could be to collect all arrays in an array and reduce the data.

var firstArray = [22, 54, 33, 10],
    secondArray = [2, 27, 11, 10],
    result = [firstArray, secondArray].reduce((a, b) => a.map((v , i) => v / b[i]));
    
console.log(result);

Upvotes: 3

knee pain
knee pain

Reputation: 620

The simplest way seems to be :

var firstArray = [22, 54, 33, 10],
secondArray = [2, 27, 11, 10];
var resultArray = firstArray.map( (e, i) => e / secondArray[i]);
console.log(resultArray);

Upvotes: 1

Jeremy M.
Jeremy M.

Reputation: 1164

You could try like that :

firstArray.forEach((item, index) => {
    resultArray[index] = item / secondArray[index];
});

Upvotes: 3

Related Questions