【问题标题】:Sum consecutive numbers in array and skipping falsy values JS对数组中的连续数字求和并跳过虚假值JS
【发布时间】:2022-12-03 16:31:48
【问题描述】:

I have an array of numbers with these values

const arr = [NaN, NaN, 1, 2, 3, NaN, NaN, 4, 5, 6, 7, NaN, 8, 9, 10, NaN, 100, 200, 300, 400, 500];

How can I sum each of these consecutive values, while skipping the false values (NaN).

Expected result:

const res = [6, 22, 27, 1500] 

So far i tried implementing reduce() but probably in the wrong way, also regular for loops didn\'t get the expected results..

  • So you don\'t just want to skip falsy values. You want to use them as separator for sub-sums, right? If so, you need to tell that in your question. Because your question doesn\'t match at all your example. And this isn\'t an IQ test: we are not supposed to guess and surmise from your example what is the formula.

标签: javascript


【解决方案1】:
【解决方案2】:
猜你喜欢
  • 2017-06-03
  • 2021-05-31
  • 2015-06-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多