有没有更好的方法在 JavaScript 中对数组项进行部分求和?

我想知道是否有更好的方法来为数组的部分总和生成性能更好的解决方案。

给定一个数组 say x = [ 0, 1, 2, 3, 4, 5 ],我生成了项目的子数组,然后计算了每个数组的总和,它给出:

[ 0, 1, 3, 6, 10, 15 ]

所以完整的代码是:

x.map((y,i)=>x.filter((t,j)=>j<=i))
 .map(ii=>ii.reduce((x,y)=>x+y,0))

我想知道平面地图或其他一些数组方法是否有不需要扩展每个子数组的解决方案。


明月笑刀无情
浏览 211回答 3
3回答

当年话下

很多,通过保持运行总数:function* partialSums(iterable) {&nbsp; &nbsp; let s = 0;&nbsp; &nbsp; for (const x of iterable) {&nbsp; &nbsp; &nbsp; &nbsp; s += x;&nbsp; &nbsp; &nbsp; &nbsp; yield s;&nbsp; &nbsp; }}const x = [0, 1, 2, 3, 4, 5];console.log(Array.from(partialSums(x)).join(', '));线性时间,在线。(您也可以直接生成数组;在下面展开。)const partialSums = arr => {&nbsp; &nbsp; let s = 0;&nbsp; &nbsp; return arr.map(x => s += x);};const x = [0, 1, 2, 3, 4, 5];console.log(partialSums(x).join(', '));

小怪兽爱吃肉

平面地图在您的情况下没有用,因为您不会试图将作为列表出现的部分结果展平,但我们可能会尝试在单个reduce 中解决您的问题:[0, 1, 2, 3, 4, 5].reduce(&nbsp; &nbsp;([arr, sum], el) => { // We pass along array and running sum&nbsp; &nbsp; &nbsp; &nbsp;const next = sum + el&nbsp; &nbsp; &nbsp; &nbsp;return [[...arr, next], next]&nbsp; &nbsp;},&nbsp; &nbsp;[[], 0] // We need to seed our reduce with empty array and accumulator for calculating running sum)[0] // Array containing array and the last sum is returned, so we need to take only the first element它还只迭代数组一次,因此与创建切片然后对它们求和的解决方案相比,它的性能可能更高一些。或者带有 的版本array.push,它重用相同的数组:[0, 1, 2, 3, 4, 5].reduce(&nbsp; &nbsp;([arr, sum], el) => { // We pass along array and running sum&nbsp; &nbsp; &nbsp; &nbsp;const next = sum + el&nbsp; &nbsp; &nbsp; &nbsp;arr.push(next)&nbsp; &nbsp; &nbsp; &nbsp;return [arr, next]&nbsp; &nbsp;},&nbsp; &nbsp;[[], 0] // We need to seed our reduce with empty array and accumulator for calculating running sum)[0]&nbsp;
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript