-1

Is there any method or quick way to see which of the elements in an array exists in a string?

const myArray = ['foo', 'bar', 'baz'];
const myString = 'somelongbarstring';

In this example, bar from the array exists in myString, so I need to get bar given myArray and myString.

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
teebeetee
  • 549
  • 1
  • 8
  • 23

1 Answers1

11

Use find with includes:

const myArray = ['foo', 'bar', 'baz'];
const myString = 'somelongbarstring';

const res = myArray.find(e => myString.includes(e));

console.log(res);

If you want to find all items included in the string, swap out find for filter:

const myArray = ['foo', 'bar', 'baz'];
const myString = 'somelongbarstring-baz';

const res = myArray.filter(e => myString.includes(e));

console.log(res);

If you want the index, use findIndex:

const myArray = ['foo', 'bar', 'baz'];
const myString = 'somelongbarstring';

const res = myArray.findIndex(e => myString.includes(e));

console.log(res);

Multiple indexes is a little tricky - you'd have to use the Array.prototype.keys method to preserve the original indexes because filter returns a new array with new indexes:

const myArray = ['foo', 'bar', 'baz'];
const myString = 'somelongbarstring-baz';

const res = [...myArray.keys()].filter((e, i, a) => myString.includes(myArray[e]));

console.log(res);

(You could also swap out e for i in the above function, but it's more understandable to do this because we're iterating through the keys.)

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79