-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.

1
  • 4
    What did you try? Commented Jul 11, 2019 at 13:09

1 Answer 1

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.)

Sign up to request clarification or add additional context in comments.

8 Comments

Or .filter for all
Edited (a lot) @JonasWilms.
@JackBashford Your last example doesn't work?
Fixed @Kobe - also thanks for the indices!
No worries, indexes sounds better but English is weird :P
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.