遍历一个数组,添加 JavaScript 中 true 出现的次数


假设我们有一个由 't'/'f' 表示的真/假的数组,我们从数据库中检索到,如下所示 −

const arr = ['f', 't', 'f', 't', 't', 't', 'f', 'f', 't', 't', 't', 't', 't', 't', 'f', 't'];

我们需要编写一个 JavaScript 函数,该函数接受一个这样的数组。我们的函数应当统计出现在两个 'f' 之间的那些 't' 的连续出现次数,并返回一个计数数组。

因此,对于上述数组,输出应如下所示 −

const output = [1, 3, 6, 1];

示例

相应的代码如下 −

const arr = ['f', 't', 'f', 't', 't', 't', 'f', 'f', 't', 't', 't', 't', 't', 't', 'f', 't'];
const countClusters = (arr = []) => {
   let res = [];
   res = arr.reduce((acc, val) => {
      const { length: l } = acc;
      if(val === 't'){
         acc[l - 1]++;
      }
      else if(acc[l - 1] !== 0){
         acc.push(0);
      };
      return acc;
   }, [0]);
   return res;
};
console.log(countClusters(arr));

输出

在控制台中的输出如下 −

[ 1, 3, 6, 1 ]

更新于: 21-11-2020

94 次浏览

开启您的职业生涯

完成课程并获得认证

开始吧
广告
© . All rights reserved.