Search code examples
angularrxjsobservablereducesubscribe

Observable array inside array, digit sum?


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


Solution

  • 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))