Pit92
Pit92

Reputation: 13

Reduce sum and subtract nested array

i have a problem with reduce.

I want to add the rest of the arrays from the first array in the array. array = [[a,b],[c,d],[e,f]] the order to come is: (a-b)+(c-d)+(e-f), but my code not work :((

my code is:

const sumAndSubtract = (numberInNestedArray) => {
  return numberInNestedArray.reduce((acc, cur, ind, arr) => {
    const firstSubtract = arr[0][0] - arr[0][1];
    const otherSubtract = acc[ind] - cur[ind];
    console.log(firstSubtract);
    console.log(otherSubtract);
    return firstSubtract + otherSubtract;
  })
}



console.log(sumAndSubtract([
  [10, 0],
  [5, 7],
  [6, 9]
]))

expect result: 10 + (-2)+(-3)

Upvotes: 0

Views: 604

Answers (3)

Nina Scholz
Nina Scholz

Reputation: 386660

You could map the subtractions and add the values later.

const
    add = (a, b) => a + b,
    subtract = (a, b) => a - b,
    sumAndSubtract = array => array
        .map(a => a.reduce(subtract))
        .reduce(add);


console.log(sumAndSubtract([[10, 0], [5, 7], [6, 9]]));

Upvotes: 1

trincot
trincot

Reputation: 350477

Use reduce as follows, where a is the accumulating sum, and b and c are the atomic values retrieved from each pair:

let result = [[10, 0], [5, 7], [6, 9]].reduce((a, [b, c]) => a+b-c, 0);
console.log(result);

In your attempt, the following is not right:

  • The expression arr[0][0] - arr[0][1]. This only looks at the first pair in the array, and does so in each iteration. Instead, you should be doing cur[0] - cur[1].

  • The expression acc[ind] - cur[ind]: ind is the index in the outer array, which takes values 0, 1 and 2 for the example input. acc[ind] is a pair, not a number and cur[ind] will at some point be an out of range reference, as cur only has two values.

  • The call to reduce should get the initial value argument, because without it, the first pair will be the initial value of acc, which you don't want: you want a number. So pass 0 as initial value argument to reduce.

  • What you call otherSubtract is already given as acc, so you actually don't need this variable.

Upvotes: 2

Mordy Stern
Mordy Stern

Reputation: 901

The shortest way to do it will be:

numberInNestedArray.reduce((acc, cur) => acc + (cur[0] - cur[1]), 0)

Upvotes: 1

Related Questions