Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fast way to compare a string with an array

I have an array with a lot of names: {'John Doe', 'Peter Shark', ...}.

Now I would like to compare and match a string for e.g. 'This is your turn John Doe, pls do it' and return the name(s), if the array contains it. The string could be a long text.

I´ve tried it like this, but it do not work:

var searchStr = "This is your turn John Doe, pls do it"

var stringArray = ["John Doe", "Peter Shark"];

return (stringArray.indexOf(searchStr) > -1)
like image 381
mm1975 Avatar asked Dec 14 '22 15:12

mm1975


2 Answers

You need to search the other way around - iterate over stringArray and check if some of the names are contained in searchStr:

var searchStr1 = "This is your turn John Doe, pls do it";
var stringArray = ["John Doe", "Peter Shark"];
console.log(stringArray.some(name => searchStr1.includes(name)));

var searchStr2 = "This is your turn Foo Bar, pls do it";
console.log(stringArray.some(name => searchStr2.includes(name)));

While some is very clean and clear, for loops are slightly faster than array methods, though it should only matter if you have tens of thousands of items to iterate over:

var searchStr = "This is your turn John Doe, pls do it";
var stringArray = ["John Doe", "Peter Shark"];

const searchFor = stringArray => {
  for (let i = 0, { length } = stringArray; i < length; i++) {
    if (searchStr.includes(stringArray[i])) return true;
  }
  return false;
};

console.log(searchFor(["John Doe", "Peter Shark"]));
console.log(searchFor(["Foo Bar", "Peter Shark"]));
like image 64
CertainPerformance Avatar answered Dec 23 '22 18:12

CertainPerformance


Regular expressions are pretty good at finding stuff quick. You can prepare the regexp ahead of time, then just reuse it later, if your stringArray stays the same:

let searchStr = "This is your turn John Doe, pls do it"
let stringArray = ["John Doe", "Peter Shark"];

let nameMatcher = new RegExp(stringArray.map(
  // https://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
  s => s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
).join('|'));

console.log(searchStr.match(nameMatcher));
like image 33
Amadan Avatar answered Dec 23 '22 17:12

Amadan