This is a two part question. The first part is converting the function below to accept any number of arrays.
function getIntersect(arr1, arr2) {
var r = [], o = {}, l = arr2.length, i, v;
for (i = 0; i < l; i++) {
o[arr2[i]] = true;
}
l = arr1.length;
for (i = 0; i < l; i++) {
v = arr1[i];
if (v in o) {
r.push(v);
}
}
return r;
}
This function snippet is thanks to Ian and Jeffrey from this post.
http://www.falsepositives.com/index.php/2009/12/01/javascript-function-to-get-the-intersect-of-2-arrays/
I am interested because the performance of using the hash table is so much better than the index method of the Underscore Utility belt and the jquery-rich-array plugin. I am aware that Jquery has a method, jQuery.inArray(), however the docs make it sound like it too uses index, and I am looking for the optimal performance solution to sort through arrays with over ten thousand elements.
The second part of my question is making it Jquery friendly. Presuming the JSON object below, using Jquery how to 1) select only the arrays1-5, load them into the function and return one array.
{
"Container1": {
"Array1": ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
"Array2": ["Sunday", "Thursday", "Friday", "Saturday"],
"Array3": ["Sunday", "Friday", "Saturday"],
"Array4": ["Sunday", "Friday", "Garbage"],
"Array5": ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
"ArrayOthers1": ["1", "6", "8", "5"],
"ArrayOthers2": ["1", "6", "8", "5"],
"ArrayOthers3": ["1", "6", "8", "5"]
}
}
The answer to the above is an array = [“Sunday”,”Friday”]
We can start by using your
getIntersect()function as a helper to a newly createdgetIntersectN()function:As for the jQuery, if you are loading the JSON from an AJAX callback, then: