简体   繁体   English

查找包含数组 A 元素的数组 B 的索引

[英]find index of array B that includes element of array A

here is the arrays:这是数组:

array A = ["a", "b", "c"];
array B = ["e", "f", "a"];

I want to find the index(s) of the element in array B which is equal to the element of array A. here it is a so the index is 2...我想找到数组 B 中元素的索引,它等于数组 A 的元素。这里是 a 所以索引是 2 ...

For each item in B, look through A. If it exists in A, push the index.对于 B 中的每一项,遍历 A。如果 A 中存在,则推送索引。

var indices = [];

for (let i = 0; i < arrayB.length; i++) {
  for (let j = 0; j < arrayA.length; j++) {
    if (arrayB[i] === arrayA[j]) {
      indices.push(i);
      break;
    }
  }
}

You can use map() and filter()您可以使用map()filter()

 var A = ["a", "b", "c"]; var B = ["e", "f", "a"]; var indexArr = B.map((i, idx) => { if(A.includes(i)) return idx; }).filter(i => i); console.log(indexArr);

Using ES6: you can do this with forEach() and indexOf()使用 ES6:你可以使用forEach()indexOf()

const A = ["a", "b", "c"];
const B = ["e", "f", "a"];
let C = [];
A.forEach((v, k)=>{
  let index = B.indexOf(v);
  if (index > 0) {
    C.push(index);
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM