在匹配项之间的 javascript 数组中查找索引

Find index in javascript array between to matches

我有一个数组,假设:

const section = [{type: TYPE_B}, {type: TYPE_A}, {type: TYPE_B}, {type: TYPE_A}, {type: TYPE_A}];

我想获取 TYPE_A 的第一个元素的索引,其中下一个元素也是 TYPE_A

这是我试过的:

const firstMatch = section.reduce((a, b) => {
   if (a.type === TYPE_A && b.type === TYPE_A) {
     return a;
   }
});

虽然这不起作用,因为它 returns 未定义所有不匹配项并且代码在下一次迭代时崩溃。

您可以使用findIndex

const section = [{type: 'TYPE_B'}, {type: 'TYPE_A'}, {type: 'TYPE_B'}, {type: 'TYPE_A'}, {type: 'TYPE_A'}];
const toFind = 'TYPE_A';

let idx = section.findIndex((o, i, a) => a[i - 1] && a[i - 1].type === toFind && a[i + 1] && a[i + 1].type === toFind && o.type !== toFind);

console.log(idx);

您可以使用 Array#findIndex 并检查所需 type 的前置元素和实际元素。

var section = [{ type: 'TYPE_B' }, { type: 'TYPE_A' }, { type: 'TYPE_B' }, { type: 'TYPE_A' }, { type: 'TYPE_A' }],
    type = 'TYPE_A',
    index = section.findIndex((o, i, a) => i && a[i - 1].type === type && o.type === type);

console.log(index);

    const section = [{
      type: 'TYPE_B'
    }, {
      type: 'TYPE_A'
    }, {
      type: 'TYPE_B'
    }, {
      type: 'TYPE_A'
    }, {
      type: 'TYPE_A'
    }];

    var first=-1,second=-1;
    
    section.forEach((typeObj,index)=>{
       if(first===-1){
         if(typeObj.type==='TYPE_A') first=index;
       }
       else if(first>=0){
         if(typeObj.type==='TYPE_A') second=index;
       }
    })
    
    if(first>=0 && second>0) console.log(first+1);
    else console.log("not found")

const section = [
  {type: "TYPE_B"},
  {type: "TYPE_A"},
  {type: "TYPE_B"},
  {type: "TYPE_A"},
  {type: "TYPE_A"}
];

for (var i = 0; i < section.length - 1; i++) {
  if (section[i].type == "TYPE_A" && section[i + 1].type == "TYPE_A") {
    console.log(i);
  }
}

注意:我在 TYPE_ATYPE_B 的每个出现处都添加了引号。如果这些是变量,请删除引号。我将它们保留在这里是因为如果解释器将它们视为变量(它们未定义),它们将 return 出错。

如果您真正想要的是找到两个后续 TYPE_A 元素的第一个索引,那么您可以按以下方式使用 findIndex

section.findIndex((e, idx, arr) => e.type === TYPE_A && arr[idx+1] && arr[idx+1].type === TYPE_A)

这将 return 与数组中的下一个元素相同的元素列表。

var TYPE_A = {"a":"a"};
var TYPE_B = {"b":"b"};
const section = [{type: TYPE_B}, {type: TYPE_A}, {type: TYPE_B}, {type: TYPE_A}, {type: TYPE_A}];

var results = [];
if (section.length > 1) {
    for(var i = 0; i < section.length -1;i++){
    if(section[i].type == section[i+1].type){
      results.push(i);
    }
  }
}
console.log(results);