【问题标题】:How to return the index from two array?如何从两个数组返回索引?
【发布时间】:2020-07-21 14:57:50
【问题描述】:

我有两个数组,我想要的结果是从匹配值中返回索引。该怎么做?

例如我有这两个数组:

const arr1 = [猴子、狮子、长颈鹿、熊、蚂蚁、鱼、恐龙]

cosnt arr2 = [狮子、长颈鹿、熊]

如何将结果作为匹配值的索引返回?

【问题讨论】:

  • 遍历一个并检查每个项目并在另一个中使用indexOf

标签: reactjs asynchronous setstate


【解决方案1】:

你可以这样试试。

const arr1 = [ 'monkey', 'lion', 'giraffe', 'bear', 'ant', 'fish', 'dinosaur' ]
const arr2 = [ 'lion', 'giraffe', 'bear' ];
let index = [];

arr2.forEach(function(a,i){
  index.push(arr1.indexOf(a));
});
console.log(index);

//another way using map function
let result = arr2.map((a,i)=>{
   return arr1.indexOf(a);
})
console.log(result);

【讨论】:

    猜你喜欢
    • 2014-02-09
    • 1970-01-01
    • 2018-11-14
    • 2019-08-15
    • 2015-01-29
    • 2022-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多