Kostas Koutoupis
Kostas Koutoupis

Reputation: 93

forEach() and reduce() not working with arguments

I have two arrays (a,b) and my task is to find the difference of their volumes i.e. i have to multiply all elements of array a, then do the same for array b and then subtract the two to find the difference.

I tried using forEach() and reduce() in conjuction with arguments but it seems that the last element of each array is left out and what I get as output is NaN.

This is my code

  function findDifference(a, b) {
  var args = Array.prototype.slice.call(arguments);
  var results = [];
  args.forEach(function(argument){
    return argument.reduce(function(a,b){
     results.push(a*b);
    });
  });
  return results;
}

and this is my output for findDifference([3, 2, 5], [1, 4, 4]);

[6, NaN, 4, NaN]

Looks like the multiplication stops with the second element of each array. Any ideas?

Upvotes: 0

Views: 348

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386680

Why not just multiply the given arrays and take the delta of the results?

function findDifference(a, b) {
    return [a, b]
        .map(a => a.reduce((a, b) => a * b))
        .reduce((a, b) => a - b);
}

console.log(findDifference([3, 2, 5], [1, 4, 4]));

With arguments.

function findDifference(a, b) {
    return Array.prototype
        .map.call(arguments, a => a.reduce((a, b) => a * b))
        .reduce((a, b) => a - b);
}

console.log(findDifference([3, 2, 5], [1, 4, 4]));

Upvotes: 1

Hassan Imam
Hassan Imam

Reputation: 22564

Instead of storing each multiplication in result array, you can store the result of all the multiplication of each array in result array.

function findDifference(a, b) {
  var args = Array.prototype.slice.call(arguments);
  var results = [];
  args.forEach(function(argument){
    results.push(argument.reduce(function(a,b){
      return a*b;
    }));
  });
  
  return results;
}
console.log(findDifference([3, 2, 5], [1, 4, 4]));

Upvotes: 1

Related Questions