1

Javascript Check if items in one array are present in another?

Oliver Sewell
  • 137
  • 11
  • 1
    this looks like a homework question. have you tried anything yet? – Cruiser Jan 10 '17 at 15:48
  • 1
    You might try searching, because this question has been asked many times before, including here: http://stackoverflow.com/q/16312528/215552 – Heretic Monkey Jan 10 '17 at 15:50
  • 1
    Possible duplicate of [Check if an array contains any element of another array in JavaScript](http://stackoverflow.com/questions/16312528/check-if-an-array-contains-any-element-of-another-array-in-javascript) – Heretic Monkey Jan 10 '17 at 15:50

2 Answers2

1
  1. Sort both arrays
  2. Iterate over the two arrays simultaneously and if the values on the same positions are not "same", return false.
  3. If you reached the end of array, return true.
Matey
  • 1,190
  • 5
  • 7
  • "Same" means, here, that the elements in b are the elements in a squared, regardless of the order. –  Jan 10 '17 at 15:56
  • The question says regardless of order though – Oliver Sewell Jan 10 '17 at 15:57
  • 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)) – Matey Jan 10 '17 at 16:01
  • I have no idea what that means – Oliver Sewell Jan 10 '17 at 16:07
  • 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. – Matey Jan 10 '17 at 16:23
0

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));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392