Oliver Sewell
Oliver Sewell

Reputation: 137

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

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

Upvotes: 1

Views: 615

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386858

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));

Upvotes: 0

Matey
Matey

Reputation: 1210

  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.

Upvotes: 1

Related Questions