简体   繁体   English

比较数组以匹配元素

[英]Compare arrays for matching elements

So I have two arrays, 所以我有两个数组

arr1 contains a list of ids: arr1包含ID列表:

var arr1 = new Array(1,2,3);

arr2 contains a list of objects having id´s matching the ids i arr1 arr2包含对象列表,这些对象的id与id arr1匹配

 var2 = [
{id:1,
name: "bob"},
{id:2,
name:"Moore"}
]

How can I 'loop' these arrays against each other and have some code happening when a match is found? 当找到匹配项时,如何使这些数组彼此“循环”并发生一些代码?

I'd use filter if I needed the matches. 如果需要比赛,我会使用filter

var matches = arr2.filter(function (item) {
  return arr1.indexOf(item.id) > -1;
});

Then I'd do what I need to with matches . 然后我会做我需要做的matches

If I just needed to see if one existed I'd use some . 如果我只想看一个是否存在,我会用some

var hasMatch = arr2.some(function (item) {
  return arr1.indexOf(item.id) > -1;
});

if (hasMatch) {
  doSomething();
}

this is an "Associative Array" 这是一个“关联数组”

   for(var i = 0;i<var2.length;i++){
     if(var2[var1[i]]){
       //do some mother trucking code
     }
   }

i was thinking something else actually. 我实际上在想别的东西。 why not just double for loop? 为什么不只是双倍循环?

for(var i = 0;i<arr1.length;i++){ for(var j = 0;j<var2.length;j++){ if(arr1[i] === var2[j].id){ //do stuff } } } 

Look, check, logic: 看,检查,逻辑:

for (var i = 0; i < arr1.length; i++) {
    for (var j = 0; j < var2.length; j++) {
        if (arr1[i] == var2[j].id) {
            //logic for match
        }
    }
}

Loop through id array checking each one against object array. 遍历id数组,将每个数组与对象数组进行检查。 Also some invalid values in object array I fixed below. 我在下面修复的对象数组中还有一些无效值。

var arr1 = new Array(1,2,3);
var arr2 = [
    {
        id:1,
        name: 'bob'
    },
    {
        id:2,
        name: 'moore'
    }
];

var results = [];
var index = 0, length = arr1.length;
for ( ; index < length; index++) {
    var subIndex = 0, subLength = arr2.length;
    for ( ; subIndex < subLength; subIndex++) {
        if (arr1[index] == arr2[subIndex].id) {
            results.push(arr2[subIndex]);
        }
    }
}
console.log(results);

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

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