JavaScript filter array by multiple strings?

JavascriptWeb DevelopmentObject Oriented Programming

To filter array by multiple strings, use for loop along with indexOf(). Following is the code −

Example

var details = [
   'My first Name is John and last Name is Smith',
   'My first Name is John and last Name is Doe',
   'Student first Name is John and last Name is Taylor'
];
var isPresent;
var records = [];
var matchWords = ['John', 'Doe'];
for (var index = 0; index < details.length; index++){
   isPresent = true;
   for (var outer = 0; outer< matchWords.length; outer++) {
      if (details[index].indexOf(matchWords[outer]) === -1) {
         isPresent = false;
         break;
      }
   }
   if (isPresent){
      records.push(details[index]);
   }
}
console.log(records)

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo151.js.

Output

This will produce the following output −

PS C:\Users\Amit\JavaScript-code> node demo151.js
[ 'My first Name is John and last Name is Doe'
raja
Published on 11-Sep-2020 12:07:45
Advertisements