【问题标题】:Finding the index of an array in an array using higher order functions?使用高阶函数在数组中查找数组的索引?
【发布时间】:2021-12-01 18:36:30
【问题描述】:

我可以找到一个数组是否存在于另一个数组中:

const arr1 = [[1,2,3],[2,2,2],[3,2,1]];

const match = [2,2,2];

// Does match exist
const exists = arr1.some(item => {
  return item.every((num, index) => {
    return match[index] === num;
  });
});

我可以找到那个数组的索引:

let index;
// Index of match
for(let x = 0; x < arr1.length; x++) {
  let result;
  for(let y = 0; y < arr1[x].length; y++) {
    if(arr1[x][y] === match[y]) { 
      result = true; 
    } else { 
      result = false; 
      break; 
    }
  }
  
  if(result === true) { 
    index = x; 
    break;
  }
}

但是使用 JS 的高阶函数可以找到索引吗?我看不到类似的问题/答案,只是语法更简洁

谢谢

【问题讨论】:

    标签: javascript arrays higher-order-functions


    【解决方案1】:

    您可以使用Array#findIndex

    const
        array = [[1, 2, 3], [2, 2, 2], [3, 2, 1]],
        match = [2, 2, 2],
        index = array.findIndex(inner => inner.every((v, i) => match[i] === v));
    
    console.log(index);

    【讨论】:

    • 啊完美,这就是我想要的组合。谢谢!
    【解决方案2】:

    另一种方法将数组的inner-arrays 转换为['1,2,3', '2,2,2', '3,2,1'] 之类的字符串,并将匹配的数组转换为字符串2,2,2。然后使用内置函数indexOf 在数组中搜索该索引。

    const arr1 = [[1,2,3],[2,2,2],[3,2,1]];
    const match = [2,2,2];
    
    const arr1Str = arr1.map(innerArr=>innerArr.toString());
    const index = arr1Str.indexOf(match.toString())
    console.log(index);

    【讨论】:

      猜你喜欢
      • 2022-11-10
      • 2020-09-03
      • 2014-02-17
      • 1970-01-01
      • 1970-01-01
      • 2014-05-08
      • 2019-07-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多