首页 > 解决方案 > 比较 2 个数组并检查位置

问题描述

我有 2 个数组,一个有 10 个元素,另一个有 3 个,我需要创建一个与最大向量大小相同的新数组,并在 3 个元素的数组中存在某个元素的位置使用布尔值检查 true

我有以下数组

array1 = [1,2,3,4,5,6,7,8,9,10]
array2 = [4,6,10]

我尝试制作 2 个 for 循环

for(var i=0; i<array1.lenght; i++){
    for(var j=0; i<array2.lenght; i++){
      if(array1[i]==array2[j]){
          array3.push(true)
      }else{
          array3.push(false)
      }
    }
}

我需要的向量是

array3 = [false, false, false, true, false, true, false, false, false, true]

标签: javascriptarraysalgorithm

解决方案


使用maplike so 和shiftlike so:

const array1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const array2 = [4, 6, 10];
const array3 = array1.map(e => {
  if (array2[0] == e) {
    array2.shift();
    return true;
  } 
  return false;
});
console.log(array3);
.as-console-wrapper { max-height: 100% !important; top: auto; }

如果您只想基本检查元素是否在数组中,而不是顺序,请使用includes.

const array1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const array2 = [4, 6, 10];
const array3 = array1.map(e => array2.includes(e));
console.log(array3);
.as-console-wrapper { max-height: 100% !important; top: auto; }


推荐阅读