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?

6
  • It will be easy with regular expressions. Commented Aug 3, 2017 at 17:54
  • array.join("|") then do regex .match, but the performance stays the same. stackoverflow.com/questions/45372093/… Commented Aug 3, 2017 at 17:54
  • Has the performance difference been tested? I'd assume with regex that it'd have a slight advantage in larger cycles. Commented Aug 3, 2017 at 17:59
  • @user1893706 refer to the snippet rajesh provided ( and ive included to my answer there) Commented Aug 3, 2017 at 18:00
  • Better in what way? Speed to completion? Less memory use? Too many possible correct answers here. Commented Aug 3, 2017 at 18:04

2 Answers 2

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)));
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

Yes, find is better than reduce in this case.

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.