user3142695
user3142695

Reputation: 17342

JS: Filter object array for partial matches

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.

Upvotes: 9

Views: 23764

Answers (3)

Mitro
Mitro

Reputation: 278

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;
}

Upvotes: 0

lleaff
lleaff

Reputation: 4319

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

Upvotes: 33

GOTO 0
GOTO 0

Reputation: 47761

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

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

Upvotes: 11

Related Questions