-3

I have long array and I want to check if one of elements from other array matches any from first array.

let name;
let list = ["Kat", "Jane", "Jack"]; // for example
let input = ["Hey", "i'm", "Jack"];
if (input.forEach(el => el.match(list))) { 
   do.something();
   name = ''; // get name somehow
}

But code above always returns null.

Jim D.
  • 45
  • 7
  • 2
    Have you even looked up what [`match` does?](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match) *The match() method retrieves the matches when matching a string against a **regular expression**.* – Liam Dec 07 '18 at 14:16
  • Or [`forEach`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) – VLAZ Dec 07 '18 at 14:17
  • 1
    https://stackoverflow.com/questions/1885557/simplest-code-for-array-intersection-in-javascript – Aritra Chakraborty Dec 07 '18 at 14:17
  • 1
    Also see *When the parameter is a string or a number, it is implicitly converted to a RegExp by using new RegExp(obj)* from that same documentation – Liam Dec 07 '18 at 14:17
  • "I want to check if one of elements...": do you mean _at least one_? _one_ is specific (which one?), _at least one_ isn't. – Andy Dec 07 '18 at 14:19
  • Possible duplicate of [Simplest code for array intersection in javascript](https://stackoverflow.com/questions/1885557/simplest-code-for-array-intersection-in-javascript) – Stephan Hogenboom Dec 07 '18 at 15:17

2 Answers2

2

forEach returns undefined so that condition can never pass. Also it appears you are misusing match.

You can instead use find and includes

let list = ["Kat", "Jane", "Jack"]; // for example
let input = ["Hey", "i'm", "Jack"];
let name = input.find(name => list.includes(name))
if (name) { 
   console.log(name)
}

Basically "find the first element in 'input' where 'list' includes that element"

Damon
  • 4,216
  • 2
  • 17
  • 27
0

You need to check if (input.includes(el)) inside your forEach loop:

let name;
let list = ["Kat", "Jane", "Jack"]; // for example
let input = ["Hey", "i'm", "Jack"];
input.forEach(el => {
  if (list.includes(el)) { 
    console.log(el + ' is in list')
  }
})
connexo
  • 53,704
  • 14
  • 91
  • 128