【问题标题】:Get number of times a negative sequence occurred in array获取数组中出现负序的次数
【发布时间】:2021-03-20 18:50:32
【问题描述】:

假设我有以下数组:

const arr = [-1, -2, -1, 0, 1, 0, -1, -2];

我想得到负数按顺序出现的次数,作为一个集合。所以对于上面的例子,它会输出2,因为我们得到了一次-1, -2, -1,,然后又得到了-1, -2

当然,我可能会做类似arr.filter(x => x < 0).length; 之类的事情来获得负面事件发生的总次数,这会给我5,但我不希望那样。我想要一组负数出现了多少次。

【问题讨论】:

  • 循环,每次符号变为负数时,递增。

标签: javascript arrays loops filter numbers


【解决方案1】:

您可以计算非负先前值a和正实际值b的变化。

let array = [-1, -2, -1, 0, 1, 0, -1, -2],
    count = array.reduce((s, b, i, { [i - 1]: a = 1}) =>
        s + (a >= 0 && b < 0),
    0);

console.log(count);

【讨论】:

    【解决方案2】:

    我们可以用不同的方式来解决,我会提出一个很酷的解决方案,因为它利用了 JS 的工作原理,我们可以用图形方式解决它:)

    
        arr
           //get rid of all non-negative numbers and change them to a white space
           .map(x => x < 0 ? x : ' ')
           //change it to string in order to...
           .join('')
           //replace any white spaces cluster to a single white space
           .replace(/\s+/g, ' ')
           //split on these single spaces
           .split(' ')
           //get rid of a single empty string which would appear if we had an empty array
           .filter(x => x)
           //return the number of negative number clusters
           .length
    
    

    【讨论】:

      猜你喜欢
      • 2016-06-09
      • 2012-06-23
      • 2011-04-16
      • 1970-01-01
      • 2010-11-06
      • 1970-01-01
      • 2011-11-30
      相关资源
      最近更新 更多