javascript - 比较 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]
解决方案
使用map
like so 和shift
like 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; }
推荐阅读
- android - 如果 Android 应用程序不在中国 Android 手机的堆栈中,则推送通知不起作用
- node.js - 节点如何同时处理多个请求?
- c# - 如何将此源变量绑定到现有文本框?
- c++ - 如何使用 clang 更快地编译?
- c# - 如何在 mvc html 标签中添加 vue?
- powershell - 如何在powershell中为此输出分配不同的变量?
- python - Plotly:雷达图将 theta 误认为是 int 而不是 string
- python - Python3 记忆游戏无法在表面上粘贴图像
- c++ - 我的刽子手艺术不会以正确的顺序打印
- python - Gurobi 约束违规