从输入创建排除过滤器
问题描述:
我正在尝试使搜索字符串识别搜索中的字符。从输入创建排除过滤器
如果文本包含-
,我想将其用作exclude
。
只有在-
字符有space before it
或position 0
时才应排除。
搜索foo -bar
它应该只在foo存在但bar没有。
我所建立的CodeSandbox样本:https://codesandbox.io/s/ZvAqXoOQ
代码应该像这样工作,但我们也承认,当应用every(e => !title
。
.filter(movie => {
const title = movie.title.toLowerCase();
return search.every(e => title.includes(e.toLowerCase()));
栏基于术语的第一个字母
.filter(movie => {
const title = movie.title.toLowerCase();
return search.every(e => !title.includes(e.toLowerCase()));
});
答
皮克条件。像这样的东西。
const movies = ['foo', 'foo bar', 'baz', 'qux', 'foo baz'].map(title => ({title}))
const search = 'foo -bar'.split(' ')
console.log(
movies.filter(
({title}) => search.every(term => term[0] === '-' ? !title.includes(term.substring(1)) : title.includes(term))
)
)
const movies = ['foo', 'foo bar', 'baz', 'qux', 'foo baz'].map(title => ({title}))
const search = 'foo -'.split(' ')
console.log(
movies.filter(
({title}) => search.every(term => {
if(term === '-') return true
if(term[0] === '-') return !title.includes(term.substring(1))
return title.includes(term)
})
)
)
一个小问题,但─如果只是' - '(与之前的空间和无文本之后目前,打字的时候将显示不出结果直到在' - '之后键入东西。示例https://codesandbox.io/s/ZvAqXoOQ – Ycon
@Ycon这个想法是一样的:根据您的需求分析术语,然后使用if-else语句来选择根据你的分析,你需要的条件。所以你检查'如果(term ===' - ')返回true'比'if(term [0] ===' - ')return!title.includes'等 –
好。最后,我试图将您的示例应用于嵌套在“电影”中的一些数据。但是,无法应用过滤器。它在这里(第12行)https://codesandbox.io/s/ZvAqXoOQ。我的尝试是'if(x [0] ==='#')返回genres.includes(f => genres.includes(x.toLowerCase())' – Ycon