Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
149
rated 0 times [  153] [ 4]  / answers: 1 / hits: 25510  / 14 Years ago, tue, november 16, 2010, 12:00:00

I have two integer arrays which contain numeric values. I want to look through both lists and check for commonality (or lack of) between the lists. I.e. I want to iterate through the array(s) and find those items which appear in both lists, while in a separate function I want to go through the arrays and find items which are in the first and not in the second.



The obvious way of doing this is nested for loops:



var containedInFirst = false;
for (var primaryID = 0; primaryID < PrimaryArray.length; primaryID++) {
containedInFirst = false;
for (var secondaryID = 0; secondaryID < SecondaryArray.length; secondaryID++) {
if (PrimaryArray [primaryID] === SecondaryArray[secondaryID]) {
containedInFirst = true;
break;
}
}

//Do some more stuff based on the value of containedInFirst here
}


But given the lists could contain hundreds or thousands of records this is quite a bit of itteration and processor intensive.
I was therefore wondering if there is a more efficient way of executing the above code? Not just the actual searching, but something more efficient than an Integer array as the container for the values, or just not using nested for loops to traverse and compare the content.



Any thoughts on more efficient or elegant solutions?


More From » arrays

 Answers
21

Sort them first and duck-waddle through them in parallel.



a.sort();
b.sort();

left = []; both = []; right = [];
i = 0; j = 0;
while (i < a.length && j < b.length) {
if (a[i] < b[j]) {
left.push(a[i]);
++i;
} else if (b[j] < a[i]) {
right.push(b[j]);
++j;
} else {
both.push(a[i]);
++i; ++j;
}
}
while (i < a.length) {
left.push(a[i]);
++i;
}
while (j < b.length) {
right.push(b[j]);
++j;
}

[#94950] Saturday, November 13, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
andreguym

Total Points: 125
Total Questions: 112
Total Answers: 103

Location: Wallis and Futuna
Member since Tue, Mar 30, 2021
3 Years ago
;