Looping through arrays

Oct 3, 2012 at 8:01 PM

I've been banging my head for seemingly forever trying to get this to work.

I'm working on a jQuery/SPServices web part that rolls up some data on audience targetted library items. Web services do not audience target, so I'm having to roll my own and running into issues.

I'm able to get back a list of audiences from the server via some cutom code and parse that out and push it into an array, userAudArray. In my SPServices GetListItems, I'm able to dump the ows_Audience field into an array, split on ; and grep it so it only lists the audiences, iAudArray.

I need to do a check to verify that at least 1 GUID in the iAudArray exists in the userAudArray so I can write it to the eventual output. If no GUID from the iAudArray is present in the userAudArray, I need to skip the item.

I've tried seemingly every thing I know of and that I can find on stackoverflow to evaluate if any item in array A exists in array B. Any pointers would be appreciated.

Oct 3, 2012 at 8:25 PM

Eric,

I hope I understood you correct... You have two arrays.  You need that at least 1 value in array 1 is present in array two... The following worked for me when I copy and pasted into Firebug's console. It display how to do it with jQuery and with native javascript... Hope this helps you...

var iAudArray = [
    "GUID value 1", 
    "GUID Value 2", 
    "GUID Value 3"
];
var userAudArray = [
    "GUID Value 2", 
    "GUID Value 4"
]; 

// Using jQuery: Loop exists teh first time a audience in the
// user group is found in the audience array.
$.each(userAudArray, function(i, v){
    if ($.grep(iAudArray, function(v2){ return v2 === v }).length) {
        console.log("1) Found user's [" + v + "] In Audienace array!");
        return false;
    }
});

// Using native javascript
for(var i=0,t=userAudArray.length; i<t; i++  ) {
    var found = false;
    console.log("test");
    for (var n=0,t2=iAudArray.length; n<t2; n++ ) {
        if (iAudArray[n] === userAudArray[i]) {
            console.log("2) Found user's [" + userAudArray[i] + "] In Audienace array!");
            found = true;
            break;
        }
    }
    if (found) { break; }
}


Paul

Oct 5, 2012 at 12:15 AM
Edited Oct 5, 2012 at 12:44 AM

I had some variable scope issues that was preventing this from working properly.  After I figured that out, it started working correctly evaluating the contents of one array against another.

 

Oct 5, 2012 at 3:38 PM

Cool..

yeah, the last time I bumped into variable scoping issues it took me 4 hours to finally realize that lexical scoping of variables in javascript is only really done at the function level; not inside blocks. 

Paul.