简体   繁体   中英

check if value exists in mulitdimensional array and return boolean

I have seen many posts about searching nested arrays in javascript but none of them have a way to tell if an item does not exist in the array.

this may sound confusing so here are some examples:

I have 2 arrays oldArray and newArray

structured like this:

array(
      [0]=>array([name]:"name"
           [location]:"location")
      [1]=>array([name]:"name2"
           [location]:"location2")
 )

both arrays are structured this way.

I need to be able to know which names exist in the old array and not in the new and vice versa.

here is what I have tried:

 var name= oldArray[key]['name'];

   for (var key in oldArray) {
       for(var i= 0, len = newArray.length; i < len; i++){
                if(newArray[i]['name'] == name){
                          //push to array
                }
                 else{
                      //push to different array
                 }
       }
 }

this way I will have an array that contains all names that exist in both arrays and an array that only contains names that exist in the oldArray..

this doesn't seem to work because it is a 1 to 1 comparison. the first array is correct but the array that should only contain the names that exist in the old array is not correct.

Have you initialized the array for old values?

Are you getting an exception?

Have you debugged it with Chrome?

edit:

I think if you do:

for all old values push if exists and ask again and push, it will keep pushing in an infinite loop.

try to add a break

    var name= oldArray[key]['name'];

       for (var key in oldArray) {
           for(var i= 0, len = newArray.length; i < len; i++){
                    if(newArray[i]['name'] == name){
                              //push to array

                    break;
                    }
                     else{
                         if(i==newArray.length-1)
                          //push to different array


                     }
           }
     }

Use a boolean to keep track of whether there is a match in the new array. Then after you complete the inner for loop over the newArray, check boolean to see if no matches were found, then push to other array.

var name= oldArray[key]['name'];

for (var key in oldArray) 
{
    var foundMatch=false
    for(var i= 0, len = newArray.length; i < len; i++)
    {
        if(newArray[i]['name'] == name)
        {
            //push to array
            foundMatch=true;
                    break;
        }
    }
    if(foundMatch==false)
    //push to different array

}

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