简体   繁体   中英

Compare arrays for matching elements

So I have two arrays,

arr1 contains a list of ids:

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

arr2 contains a list of objects having id´s matching the ids i 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.

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

Then I'd do what I need to with matches .

If I just needed to see if one existed I'd use 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. 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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