0

I was thinking about doing an array to make my current string.includes() || string.includes()... code shorter, as checking for many words can make that list long, but I couldn't find an easy way to replicate this with array.

array.includes(string) only seems to check is the string specifically that, so if there's something else in that string too it wont work, which is pretty much the opposite of what I'm trying to do.

Help much appreciated.

1
  • There are other array methods? Like some, every, filter, etc Commented Jan 9, 2021 at 13:23

2 Answers 2

2

You could try this

const myString = "Hello";
const arrayOfStrings = ["H", "U", "W"];

const hasString = arrayOfStrings.some(el => myString.includes(el))

console.log(hasString)

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

Comments

1

It seems like you don't only want to make string.includes() || string.includes()... shorter, but you also want to output all strings that are a substring as a collection, you can use map and filter falsey outputs, like this:

let array = ["ab", "a", "abc", "abd", "cd", "ce"];

let res = array.map(e=>"abcdef".includes(e)?e:null).filter(e=>e!=null)

console.log(res);

If you still want true/false output, you can use reduce, like this:

let array = ["ab", "a", "abc", "abd", "cd", "ce"];

let res = array.map(e=>"abcdef".includes(e)).reduce((a,b)=>a||b,false)

console.log(res);

2 Comments

What I'm trying to do is more like that a string would be a full sentence, and if that sentence includes a word listed in an array, it would then run a piece of code with if.
Then the second snippet is what you will need :) Instead of "abcdef", use your sentence.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.