Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 691
user3142695 Avatar asked Feb 04 '17 02:02

user3142695


People also ask

How to do a partial match on an array in JavaScript?

By combining expect.objectContaining and expect.arrayContaining we can do a partial match on the objects in the array: Note: the parameter passed to arrayContaining must be an array, even if that array contains expect.objectContaining partial matches

How to filter an array of objects in JavaScript?

Filter an Array of Objects in JavaScript. JavaScript arrays have a filter () method that let you create a new array containing only elements that pass a certain test. In other words, filter () gives you a new array containing just the elements you need.

What is the syntax of the filter () method in JavaScript?

The following illustrates the syntax of the filter () method: The filter () method creates a new array with all the elements that pass the test implemented by the callback () function. Internally, the filter () method iterates over each element of the array and pass each element to the callback function.

How does the array filter () method work?

The filter () method accepts two named arguments: a callback function and an optional object. Like other iterative methods of the Array object such as every (), some (), map () and forEach (), the callback function has the following form:


2 Answers

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()))
like image 170
lleaff Avatar answered Sep 18 '22 13:09

lleaff


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

arr.filter(x => x.title.includes(searchStr));
like image 40
GOTO 0 Avatar answered Sep 19 '22 13:09

GOTO 0