DEV Community

Discussion on: The moment I realized forEach() does not return anything.

Collapse
 
gautierlepire profile image
Gautier Le Pire

Hi! You might be looking for a function named Array.some. It checks that at least one item in an array verifies a given predicate, and is early-terminating.

Here's the code using a hash table (so both arrays must contain only strings) as you did:

const haveCommonItems = (array1, array2) => {
    let hashTable = {}
    array1.forEach(item => hashTable[item] = true)
    return array2.some(item => hashTable[item])
}

:)

Collapse
 
kaynguyen profile image
Kay N.

Yes that sure does the job <3! Thanks for recommending!

Collapse
 
tbroyer profile image
Thomas Broyer

And you may want to use new Set(array1) instead of your hashTable.

const haveCommonItems = (array1, array2) => {
    const array1set = new Set(array1)
    return array2.some(array1set.has)
}

(disclaimer: untested code snippet)

Thread Thread
 
kaynguyen profile image
Kay N.

Awesome! Here's my tested code:

const haveCommonItems = (array1, array2) => {
    const array1set = new Set(array1);
    return array2.some(item => array1set.has(item));

haveCommonItems(animals, pets); // returns "true"
}

Very clean and time optimized! Thanks again everyone!