javascript - 在数组中定位重复项并获取它们之间的长度

标签 javascript arrays

我得到了这样一个数组

const array = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1]

我想要的是定位这些零并获得这些零之间的个数,然后返回它们的最大长度,所以在这种情况下它将返回 5 如果是这样的话

const array = [1,0,0,0,0,0,1] 

那么输出应该是 5 如果像这样在数组中只有一个

const array = [1,0,0,0]

我应该犯错

我试过像这样使用 .findIndex() 找到第一个

const firstOneIndex = intoArray.findIndex(el => el = 1);

最佳答案

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

function getDiff(array) {
  // identify the 1's in the array
  // strip the array down to a list of only the ones with values.
  var mapped = array.map((v, i) => {
    if (v == 1) return i;
  }).filter(v => v != undefined);

  var max = 0
  var start;
  var end;
  // identify the largest gap between 1's
  for (var ind in mapped) {
    var gap = mapped[ind] - mapped[ind - 1];
    // store largest gap start and stop indexs
    if (gap > max) {
      start = ind - 1;
      end = ind;
      max = gap;
    }
  }
  
  // we do mapped[end] +1 because we want to include the last 1 in the splice, not exclude it.
  var splice = array.splice(mapped[start], mapped[end] + 1);

  return splice;
}

console.log(getDiff(arr));

关于javascript - 在数组中定位重复项并获取它们之间的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57154739/

相关文章:

xml - Bash 将 XML 解析为数组

Javascript foreach 不适用于所有对象

javascript - classList.remove ["active"] 没有按我的预期工作

java - 在 main() 中返回数组

Javascript 检查函数的结果是否已输出,如果是,则运行该函数

javascript - Chrome : Notifications not working, 未请求权限

c++ - 打印出数组成员错误的对象

c - 数组在通过 void 函数后没有改变

javascript - 如何使用 javascript 将 tr 移动到 tbody 中?

javascript - 防止页面在 DOM 操作后滚动