0

What is the most efficient way to find out if a JavaScript array contains substring of a given string?

For example in case I have a JavaScript array

var a = ["John","Jerry","Ted"];

I need the condition which returns true when I compare the above array against the string:

"John Elton"
3

3 Answers 3

4

For ES6:

var array = ["John","Jerry","Ted"];
var strToMatch = "John Elton"
array.some(el => strToMatch.includes(el))
4

You can use .some() and .includes() methods:

let arr = ["John","Jerry","Ted"];
let str = "John Elton";

let checker = (arr, str) => arr.some(s => str.includes(s));

console.log(checker(arr, str));

0

In case you cannot use ES6:

let arr = ["John","Jerry","Ted"];
let str = "John Elton";

var match = arr.some(function (name) {
  return str.indexOf(name) > -1;
});

console.log(match);

Not the answer you're looking for? Browse other questions tagged or ask your own question.