【问题标题】: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?如何检索和收集数组项目第一次出现的索引,同时考虑相同项目的连续顺序?
【发布时间】:2020-12-25 10:14:52
【问题描述】:

我正在计算连续零并将每个零视为单独的块并将其推送到像这样 [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;

【问题讨论】:

    标签: javascript arrays algorithm reduce


    【解决方案1】:

    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)

    【讨论】:

      【解决方案2】:

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

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

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

      下一次迭代将前一次/当前迭代的返回值再次视为collector/list

      因此,对于 OP 的示例,需要返回一个数组,对于每次迭代,该数组要么连接当前的 idx,以防找到连续零序列的第一个 0 值(因此条件 . .. (item === 0 &amp;&amp; arr[idx - 1] !== 0)) 或者连接一个空数组并返回这个结果...

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

      【讨论】:

      • @Sue ...出于好奇...为什么从已经接受的答案中删除了标志...或者...没有向您解释得足够好以便您拥有从现在接受的答案中更好地了解如何最好地解决问题?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-15
      • 2016-12-23
      • 2013-03-25
      • 2014-04-11
      • 1970-01-01
      • 2014-01-30
      • 2020-03-12
      相关资源
      最近更新 更多