开发者问题收集

如何在数组内搜索过滤器数组项

2022-01-16
1146

我的问题是我想找到我想要搜索的每个标题电影的类别。例如

searchInput = Action

outputShown = [Transformer,Dinosaur, Godzilla]

因为我有如下所示的类别:

    const category = ['Comedy','Classic','Drama','Romance','Science- 
     Fiction','Adult','Sex','Kids','Animation','Cartoon','Action','Storyline','Tragic']

我希望此 TitleItems 与我的搜索输入匹配,即使它们具有不同类型的类别。

    const TitleItems =  {
            imgPath:'', name:'The Office',type:['Comedy','Classic','Romance'],views:"5666",rate:"4.1"
        },
        {
            imgPath:'', name:'Ready Player One',type:['Science-Fiction','Romance','Drama'],views:"7776",rate:"4.2"
        },
        {
            imgPath:'', name:'Interstellar',type:['Science-Fiction','Drama','Romance','Tragic'],views:"10505",rate:"4.5"
        },
        {
            imgPath:'', name:'Transformer',type:['Science-Fiction','Action','Classic','Comedy'],views:"20015",rate:"4.3"
        },
        {
            imgPath:'', name:'Jack N The Giant',type:['Science-Fiction','Action','Adult','Comedy'],views:"12234",rate:"4.2"
        }

如您所见,这是搜索输入,我唯一的问题是 item.type,因为它有一个数组 我不能将其作为 item.type.toLowerCase().includes(search.toLowerCase()) 来执行,但我可以将其作为 item.type[0].toLowerCase().includes(search.toLowerCase()) 来执行,因为它不能包含数组,但我真正想做的是必须在该数组中搜索标题的每个项目类型。所以我想知道这会如何运作?有人知道吗?我不知道我问的问题是否正确。如果这是一个糟糕的问题,请帮我编辑一下。

    const [search,setsearch] = useState("");

    const ListItems = items.filter((item,index) => {
        return (
            item.name.toLowerCase().includes(search.toLowerCase()) ||
            item.views.toLowerCase().includes(search.toLowerCase()) ||
            item.rate.toLowerCase().includes(search.toLowerCase()) || 
            item.type.toLowerCase().includes(search.toLowerCase())
        )   
    }).map((item,index) => {
        return(
            <div>
                <h1 key={index}> 
                    {item.name}, {item.type} {item.views} {item.rate} 
                </h1>

            </div>

        )
    })

以下是显示输出的正文

    <input type="text" name='search' placeholder='Search...' value={search} onChange={e => setsearch(e.target.value)} />
     {ListItems}
2个回答
Amila Senadheera
2022-01-16

您需要循环遍历列表,并在该列表中添加包含该过滤文本的任何类别。

您将使用两个数组方法, forEachsome

对您的问题的简单解释:

// example from your scenario
const TitleItems: { id: number, list: string[] }[] = [
    {
        id: 12,
        list: ['1', '2', '3', '4', '5', '6', '7', '8']
    }
]

// the accumulator function that shall be taking in the values that have passed our given test
let accumulator: any[] = []

// first loop through all the items by forEach
TitleItems.forEach((item) => {

// then use a comparison using some, some will return true when any element in it matches the query you put
// the query should be your search string
if (item.list.some(item => item === '12')) {
    accumulator.push(item)
}
})

最后,您的累加器数组将具有已通过该条件的值....

对于一个非常高级的解决方案,我不建议初学者使用数组 Reduce 函数来解决这种情况。

此处 了解有关 some 方法的更多信息

emanuel sanga
2022-01-16