9

Is it possible to filter for those objects, which matches for a search string?

const arr = [
    { title: 'Just an example' },
    { title: 'Another exam'},
    { title: 'Something different'}
]

I tried this

arr.filter(x => { return x.title === searchStr });

But this will filter only exact matches, but I need to find all partial matches. let searchStr = 'exam' should give me two objects (first and second), let searchStr = 'examp' should give me only one object as the result.

1
  • x.title.indexOf(searchStr) !== -1? Commented Feb 4, 2017 at 2:08

3 Answers 3

33

From your question I will assume you also want to match both uppercase and lowercase versions of your string, so here RegExps are the right (but not the only) choice.

RegExp solution:

First, define a case-insensitive RegExp with the i flag, outside of the loop (this avoids re-creating a new RegExp instance on each iteration):

 const regexp = new RegExp(searchStr, 'i');

Then you can filter the list with RegExp#test (String#match would work too):

arr.filter(x => regexp.test(x.title))

String#includes solution:

You could also use the .includes method of String, converting both strings to lowercase before comparing them:

arr.filter(x => x.title.toLowerCase().includes(searchStr.toLowerCase()))
Sign up to request clarification or add additional context in comments.

1 Comment

There is one closing bracket too much: arr.filter(x => regexp.test(x))) and for this question you have to use x.title instead of x... ;-)
11

Since you are using ES6, use the includes method to test for the substring.

arr.filter(x => x.title.includes(searchStr));

Comments

0

You can check with the indexOf and also add toLowerCase() method to increase the possibility of a match

myArr.filter(function(x) { 
    return x.title.toLowerCase().indexOf(searchString.toLowerCase()) > -1;
}

Comments

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.