如何在考虑相同项目的连续顺序的情况下检索和收集数组项目第一次出现的索引?

How does one retrieve and collect the index of an array item's first occurrence also taking a consecutive order of same items into account?

我正在计算连续零并将每个零视为单独的块并将其推送到数组块,如 [3,1,1],我需要做的是推送位置另一个数组中每个块中的第一个元素,如 [2,13,15]

var A = [1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0];
var N = A.length
function Avaiblocks(A,N,X){
  var counter = 0;
  var Blocks = [];
  var POS =[];
    
  for(var i = 0; i < A.length; i++) {
      if(A[i] === 0){
          counter++;
          POS.push(i) 
        } else {
            if (counter !== 0) {
                Blocks.push(counter)
                counter = 0;
            }
        }
    }
    if (counter !== 0){
      Blocks.push(counter)
        }
return POS;

Array.prototype.reduce迭代给定的数组。

将 reducer 函数和一个额外的空数组作为收集器传递给它。

对于每次迭代,reduce 函数都可以访问其收集器(此处为 list)、当前处理的 item、当前的 idx(索引)和处理的 arr(数组)本身。

下一次迭代将 former/current 迭代的 return 值再次视为收集器/list

因此,对于 OP 的示例,需要 return 一个数组,对于每次迭代,如果序列的第一个 0 值,则连接当前 idx找到了连续的零(因此条件...(item === 0 && arr[idx - 1] !== 0))或者确实连接了一个空数组并且returns这个结果...

function collectIndexOfFirstOneOfConsecutiveZeros(list, item, idx, arr) {
  return list.concat(
    (item === 0 && arr[idx - 1] !== 0)
    ? idx
    : []
  );
}
const sampleList = [1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0];

console.log(
  sampleList.reduce(collectIndexOfFirstOneOfConsecutiveZeros, [])
);

// ... or directly like ...

console.log(
  [1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0]
    .reduce((list, item, idx, arr) =>
      list.concat((item === 0 && arr[idx - 1] !== 0) ? idx : []),
      []
    )
);

let arr = [1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0]

let result = Array.from(arr.join("").matchAll(/0+/g),m=>m['index'])

console.log(result)