Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Array.find Regex

I have 2 arrays of keywords. I need to figure out the index of the first keyword in array 1 that matches any of the keywords in array 2.

Examples

array1 = ['spinach', 'avocado', 'milk', 'beans', 'ham', 'eggs', 'cheese'];
array2 = ['cheese', 'milk'];

In this example, milk at index 2 would be the first match, and I want to return the index of 2.

Can I use array.find() to return the index of the first match, if each element is compared to array2 using regex?

like image 452
Matthew Rideout Avatar asked Oct 20 '25 04:10

Matthew Rideout


2 Answers

You could use Array#findIndex and check the second array with Array#includes.

var array1 = ['spinach', 'avocado', 'milk', 'beans', 'ham', 'eggs', 'cheese'],
    array2 = ['cheese', 'milk'];
    
console.log(array1.findIndex(v => array2.includes(v)));
like image 193
Nina Scholz Avatar answered Oct 21 '25 17:10

Nina Scholz


You can find matching index using findIndex() and includes():

let index = array1.findIndex(s => array2.includes(s));

Demo:

let a1 = ['spinach', 'avocado', 'milk', 'beans', 'ham', 'eggs', 'cheese'],
    a2 = ['cheese', 'milk'];

let index = a1.findIndex(s => a2.includes(s));

console.log(index);

Docs:

  • Array.prototype.findIndex()
  • Array.prototype.includes()
  • Arrow Functions
like image 43
Mohammad Usman Avatar answered Oct 21 '25 16:10

Mohammad Usman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!