Javascript Check if items in one array are present in another?
-
1this looks like a homework question. have you tried anything yet?Cruiser– Cruiser2017-01-10 15:48:59 +00:00Commented Jan 10, 2017 at 15:48
-
1You might try searching, because this question has been asked many times before, including here: stackoverflow.com/q/16312528/215552Heretic Monkey– Heretic Monkey2017-01-10 15:50:36 +00:00Commented Jan 10, 2017 at 15:50
-
1Possible duplicate of Check if an array contains any element of another array in JavaScriptHeretic Monkey– Heretic Monkey2017-01-10 15:50:42 +00:00Commented Jan 10, 2017 at 15:50
Add a comment
|
2 Answers
- Sort both arrays
- Iterate over the two arrays simultaneously and if the values on the same positions are not "same", return false.
- If you reached the end of array, return true.
5 Comments
Oliver Sewell
The question says regardless of order though
Matey
Regardless of order means you are free to change the order of array items (e.g. by sorting the array). Yes, you can do it without sorting but that would result in O(n^2) complexity instead of O(n*log(n))
Oliver Sewell
I have no idea what that means
Matey
Basically, the most general way to check for the "sameness" of two arrays if to compare each item in array A to each item in array B. Which is a hell of a lot comparisons. If you sort the arrays first you don't need to compare each item to each item and the program will finish much sooner. I recommend learning about algorithms and complexity if you take programming seriously.
You could use a hash table and check the first array for same hashes. Then return the common numbers.
function comp(array1, array2) {
var hash = {};
array2.forEach(function(a) {
hash[Math.sqrt(a).toString()] = true;
});
return array1.filter(function (a) {
return hash[a];
});
}
var array1 = [121, 144, 19, 161, 19, 144, 19, 11],
array2 = [11, 14641, 20736, 361, 25921, 361, 20736, 361];
console.log(comp(array1, array2));