2017-06-16 3 views
0

からフィルターを除外する作成します。は、私は、検索から文字を認識し、検索文字列を作成しようとしています入力

私はテキストが-が含まれている場合excludeようにそれを使用したいです。

-文字がspace before itであるか、またはposition 0である場合にのみ除外する必要があります。それはfooが存在している必要がありますだけでなく、バ​​ーにはない

検索foo -bar

私はCodeSandbox上のサンプルを作成しました:https://codesandbox.io/s/ZvAqXoOQ

コードは次のように動作しますが、every(e => !titleを適用する際に認識すべきです。用語の最初の文字に基づいて

fooの

.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())); 
}); 

答えて

1

ピック状態。このようなもの。

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

+0

that-の一つの小さな問題 '場合のみ - 。の前にスペースと後のテキストなしで'(入力したときに、現在、それは結果が表示されません。「 - 」何かが後に入力されるまで、ここで例https://codesandbox.io/s/ZvAqXoOQ – Ycon

+0

@Ycon考え方は同じである:あなたのreqirementsによる用語を分析し、次に選択するのif-elseステートメントを使用しますあなたの分析に基づいて必要な条件。 (用語[0] === ' - ')場合は 'よりもリターンtrue'を返すtitle.includes'など –

+0

グレートを - だから、( '' ===用語)場合'チェック!。最後に、私はあなたの例を「映画」の中にネストされたいくつかのデータに適用しようとしています。ただし、フィルタを適用できません。それはここです(12行目)https://codesandbox.io/s/ZvAqXoOQ。 – Ycon

関連する問題