数组中的可观察数组,数字总和?

问题描述 投票:0回答:1

我有一个可能有嵌套数组的数组。无论有多少'子'阵列,我想总结父母内部的所有数字。

为什么不以这种方式工作。其他人抱怨acc1是一个阵列,这是正常的但仍然,这种方法有什么问题?

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

结果应该是16

angular rxjs observable reduce subscribe
1个回答
2
投票

你非常接近:

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))
© www.soinside.com 2019 - 2024. All rights reserved.