0

I have an array which may have nested arrays. I want to sum all numbers inside the parent no matter how many 'child' arrays are there.

Why doesn't it work this way. The else is complaining about acc1 being an array, which is normal but still, what's the problem with this approach?

Observable.from([1, 2, 3, [ 1, 2, 3, 4]])
    .map(x => x)
    .reduce((acc1, y) => {
      if (Array.isArray(y)) {
        return (y.reduce((acc2, x) => acc2 + x));
      } else {
        return acc1 + y;
      }
    })
    .subscribe(res => console.log(res))

Result should be 16

1 Answer 1

2

You were very close:

Observable.from([1, 2, 3, [ 1, 2, 3, 4]])
    .map(x => x)
    .reduce((acc1, y) => {
      if (Array.isArray(y)) {
        return acc1 + (y.reduce((acc2, x) => acc2 + x)); // just add acc1 to your reduced array
      } else {
        return acc1 + y;
      }
    })
    .subscribe(res => console.log(res))
Sign up to request clarification or add additional context in comments.

2 Comments

Two things to notice here: 1) the .map(x => x) is useless, taking a value and returning the same value does not make sense. 2) If you want to have update of the result not only at the end but for every value passing down the stream, instead of using reduce (the one on observable), you could use scan :)
I know it is. But I have to have an array in order to apply reduce. If I don't have map then reduce can not be applied directly on a observable array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.