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