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?

Viewed 63

I am counting the Consecutive Zeros and treating each one as separate block and pushing it to array blocks like this [3,1,1] , what i need to do is to push the position of first element in each block in another array like this [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;
2 Answers

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)

Iterate the given array with Array.prototype.reduce.

Pass the reducer function and an additional empty array as collector to it.

For each iteration the reduce function has access to its collector (here list), the currently processed item, the current idx(index) and the processed arr(array) itself.

The next iteration treats the return value of the former/current iteration as collector/list again.

Thus, for the OP's example, one needs to return an array which, for each iteration, either concats the current idx in case the first 0 value of a sequence of consecutive zeros was found (hence the condition ... (item === 0 && arr[idx - 1] !== 0)) or does concat an empty array and returns this result ...

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 : []),
      []
    )
);

Related