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.
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
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.
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.
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:
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.
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))
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()))
Since you are using ES6, use the includes
method to test for the substring.
arr.filter(x => x.title.includes(searchStr));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With