Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
462 views
in Technique[技术] by (71.8m points)

javascript - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...