I have a function that pushes values into an array (very simplified example below):
numOfArr = 3; //is dynamically retrieved. can be 1-500);
arr1 = [212,214,215,218]
arr2 = [212,259,214,292,218]
arr3 = [272,214,218,292]
I run a for loop on each of the "arr" arrays to push their values into "myArr" (which works fine) and use this to get the values that are in "arr1" AND in "arr2" through "arr500", etc. I tried to do was to iterate through myArr, create a temporary copy of the array, and using .indexOf to check for other values before removing them, but I know I'm making a mistake somewhere that I can't find..
for(var i = 0; i < myArr.length; i++){
tempArr = myArr;
for(var j = 0; j < numOfArr; j++){
var spl = tempArr.indexOf(myArr[i]);
if(spl == -1 && myArr.indexOf(myArr[i]) !== -1){
myArr.splice(i,1);
} else {
tempArr.splice(i,1);
}
}
}
Ideally, what I want is "myArr" to only end up with the values that are in all 3 arr arrays (214 and 218). Is the issue in where I remove splice on myArr because the loop is still going through everything?
Update:
Using the example here: Simplest code for array intersection in javascript
function intersect_safe(a, b)
{
var ai=0, bi=0;
var result = new Array();
while( ai < a.length && bi < b.length )
{
if (a[ai] < b[bi] ){ ai++; }
else if (a[ai] > b[bi] ){ bi++; }
else /* they're equal */
{
result.push(a[ai]);
ai++;
bi++;
}
}
return result;
}
I tried to implement it in my code as I need.
var allItems = [];
var items = [1,2,3,4,5,6,7]
allItems.push(items);
allItems.push([1,2,4,9,100,1000])
allItems.push([1,2,3,4,5,9,100])
for(var i=0; i < allItems.length; i++){
//iterate through item
console.log("items "+ items);
console.log("allItems id: "+allItems[i]);
items = intersect_safe(items,allItems[i]);
console.log("items: "+items);
}
If I use the function on the actual values that are in each index of the array, I see a proper intersection is returned so that I only have "1,2,4" as values in the final "items" array. In this loop, the function seems to return the original value every time. Apologies for missing anything blatant... I just can't find a break in the logic if each index in the array contains an array itself that I can dig deeper into.