Categories
JavaScript Answers

How to check if a string contains any element of an array in JavaScript?

Spread the love

To check if a string contains any element of an array in JavaScript, we call the filter method.

For instance, we write

const arr = ["banana", "monkey banana", "apple", "kiwi", "orange"];

const checker = (value) =>
  !["banana", "apple"].some((element) => value.includes(element));

console.log(arr.filter(checker));

to call arr.filter with the checker function.

In checker, we check if there’re any strings that include 'banana' or 'apple' in value in the arr array with includes.

some returns true if its callback returns true.

So we negate it to find the values in arr that don’t include 'banana' or 'apple'.

filter returns an array with the strings that don’t include 'banana' or 'apple'.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *