Search code examples
javascriptarraysfind-occurrences

Find the first occurrence of element from array in another array


I'm curious if there is a good way to find the first occurrence of element from array in another array. As result, the answer should be a null (if no elements from the first array in the second array) or this element. Ex.1:

fromArr = ["Yellow", "Green", "Orange", "Apple", "Banana", "Apple"];
whereArr= ["Apple", "Orange", "Banana", "Apple"];

//the answer should be "Orange", as the order counts (first we check for "Yellow", then for "Green", then for "Orange" - occurrence found!).

Ex.2:

fromArr = ["Orange", "Apple", "Banana", "Apple"];
whereArr= ["November", "December", "April", "Banana"];

//the answer should be "Banana".

Ex.3:

fromArr = ["Orange", "Apple"];
whereArr= ["November", "December", "April"];

//the answer should be null.

Thank you


Solution

  • You can use .find() on your fromArr, and convert your whereArr to a Set to allow for efficient (sublinear) lookup. .find() will loop through all your values in fromArr until the callback returns true. Once the callback returns true, .find() will return the value you're currently iterated on. You can check if the set has the value by using .has(), which will return true when a value is within the set. If find's callback doesn't return true for any values inside your fromArr, it will result in undefined.

    See example below:

    const fromArr = ["Yellow", "Green", "Orange", "Apple", "Banana", "Apple"];
    const whereSet = new Set(["Apple", "Orange", "Banana", "Apple"]);
    
    const result = fromArr.find(val => whereSet.has(val));
    console.log(result);