我得到了这样一个数组
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/