0

I am attempting to create a search function which should be able to find multiple file types given various search parameters.

For example i'd like to feed my application the following filter array ['.ini', '.exe', 'dsak_'] and compare each file found against that array to determine if the filename includes one of those strings

Currently I am using the following code

for(var i = 0; i < filter.length; i++){
  if(file.includes(filter[i])) results.push(file);
}

But I was hoping to see if there was a better way to achieve this?

Kontra
  • 93
  • 9

2 Answers2

1

I think you are looking for the following code:

files.filter((file) => 
    // apply filters on files to check if it matches
     filters.some((filter) => file.includes(filter))       
)
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
Frilox
  • 815
  • 2
  • 13
  • 24
1

Array.prototype.filter can help you find any files that match at least one filter and Array.prototype.some will ensure that you stop once the first matching filter is found:

var matchingFiles = files.filter(file => filters.some(filter => file.includes(filter)));
Noah Freitas
  • 17,240
  • 10
  • 50
  • 67