【问题标题】:Find Index where Two Arrays have same Value查找两个数组具有相同值的索引
【发布时间】:2021-02-19 01:52:45
【问题描述】:

如果我有两个数组,在 Javascript 中:

let arr1 = ["Dog", "Cat", "Monkey", "Zebra", "Goat", "Goose"];
let arr2 = ["Zebra", "Goat"];

如何找到匹配的较大数组的索引并将它们存储在另一个数组中,因此示例输出为:

let indexes = [3,4]

【问题讨论】:

    标签: javascript arrays


    【解决方案1】:

    您可以使用Array.mapArray.findIndex 实现预期输出

    let arr1 = ["Dog", "Cat", "Monkey", "Zebra", "Goat", "Goose"];
    let arr2 = ["Zebra", "Goat"];
    
    const findIndexes = (param1, param2) => {
      let arr1 = [...param1];
      let arr2 = [...param2];
      //swap the arrays if the no.of array elements 
      //in the second array are greater than first
      if(arr1.length < arr2.length) {
        [arr1, arr2] = [arr2, arr1];
      }
      //Loop through all the items of the smaller array
      //check if the element is present in the bigger array
      return arr2.map(a2 => arr1.findIndex(a1 => a1 === a2));
    }
    
    console.log(findIndexes(arr1, arr2));
    
    //here for "test", we'll get index as -1, because
    //if the matching element is not found, findIndex will 
    //return -1
    let arr3 = ["Cat", "Goose", "test"];
    console.log(findIndexes(arr3, arr1));

    如果您希望获取找到的元素的索引并希望过滤掉所有-1s,下面是相同的代码。

    let arr1 = ["Dog", "Cat", "Monkey", "Zebra", "Goat", "Goose"];
    let arr2 = ["Zebra", "Goat"];
    
    const findIndexes = (param1, param2) => {
      let arr1 = [...param1];
      let arr2 = [...param2];
      if(arr1.length < arr2.length) {
        [arr1, arr2] = [arr2, arr1];
      }
      return arr2.map(a2 => arr1.findIndex(a1 => a1 === a2)).filter(ele => ele !== -1);
    }
    
    console.log(findIndexes(arr1, arr2));
    
    let arr3 = ["Cat", "Goose", "test"];
    console.log(findIndexes(arr3, arr1));

    【讨论】:

    • 这很好——但它不能处理缺失的元素。我想过滤掉-1?
    • @akaphenom,我故意没有删除缺失元素的 -1。如果相应的元素不存在,那么许多 -1 将出现在输出中。
    【解决方案2】:
    let arr1 = ["Dog", "Cat", "Monkey", "Zebra", "Goat", "Goose"];
    let arr2 = ["Zebra", "Goat"];
    let indexes = []
    
    arr1.forEach((item, index) => {
      if(arr2.includes(item)){
        indexes.push(index)
      }
    })
    
    console.log(indexes)
    

    【讨论】:

      【解决方案3】:

      您可以通过映射您的搜索团队 (arr2) 然后在源数组 (arr1) 上使用 findIndex 方法来做到这一点,如下所示:

      let arr1 = ["Dog", "Cat", "Monkey", "Zebra", "Goat", "Goose"];
      let arr2 = ["Zebra", "Goat"];
      
      const result = arr2.map(searchTerm => arr1.findIndex((compareTerm) => compareTerm === searchTerm));
      
      console.log(result);

      【讨论】:

        猜你喜欢
        • 2018-10-13
        • 2018-03-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-02-03
        • 2022-12-12
        • 1970-01-01
        • 2020-03-08
        相关资源
        最近更新 更多