简体   繁体   English

如何过滤数组中的字符串?

[英]how to filter strings in array?

I was trying to search for function.我试图搜索 function。 This function checks the nested array, which has multiple strings, then returns if the array has a search word.这个 function 检查嵌套数组,它有多个字符串,如果数组有搜索词则返回。

The data structure of the array数组的数据结构

[
  {
   name:'aa',
   searchWords:['aa','ab','bc'] <- I want to use this array for search
  },
  {
   name:'bb',
   searchWords:['bb','bc','de'] <- I want to use this array for search
  },
...
]

I tried to use indexOf function.我尝试使用 indexOf function。
However, I couldn't display any components with this code below.但是,我无法使用下面的代码显示任何组件。
But I changed target value from item.searchWords to item.name in the code.但是我在代码中将目标值从item.searchWords更改为item.name it worked.有效。

HTML
<div className="itemWrapper">
     {filterItems.map((item, idx) => (
            <Item key={idx} {...item} id={idx} list={list} />
      ))}
</div>    


Js
const filterItems = list.filter(
      (item) => item.searchWords.indexOf(searchWord) !== -1,
    );

My desired result is that search result update in realtime.我想要的结果是搜索结果实时更新。
For instance with the same data structure above, when the user searches 'a', searchWords 'aa' and 'ab' returns true for displaying the item,例如上面相同的数据结构,当用户搜索'a'时,searchWords 'aa'和'ab'返回true以显示项目,

Thank you so much for your help.非常感谢你的帮助。

You need to loop over the searchWords array to find if it matches the search word.您需要遍历 searchWords 数组以查找它是否与搜索词匹配。 This one will work这个会起作用
const filterItems = list.filter( (item) => item.searchWords.filter((myWord) => myWord.indexOf(searchWord)>-1) );

You can try with find() and includes() on name property of the object and finally filter() .您可以尝试在 object 的 name 属性上使用find()includes() ,最后使用filter()

Demo:演示:

 var list = [ { name:'aa', searchWords:['aa','ab','bc'] }, { name:'bb', searchWords:['bb','bc','de'] } ] document.getElementById('searchWord').addEventListener('input', function(){ console.clear(); var filterItems = list.find(item => item.name.includes(this.value)); filterItems = filterItems? filterItems.searchWords: []; filterItems = filterItems.filter(i => i.includes(this.value)); console.log(filterItems); });
 <input id="searchWord"/>

You can use array#reduce and filter searchWords array using the array#filter by checking the search words.您可以使用array#reduce并通过检查搜索词使用array#filter过滤searchWords数组。

 const dataSource = [{ name: 'aa', searchWords: ['aa', 'ab', 'bc'] }, { name: 'bb', searchWords: ['bb', 'bc', 'de'] } ], searchWord = 'a', result = dataSource.reduce((res, {name, searchWords}) => { let matched = searchWords.filter(word => word.includes(searchWord)); if(matched.length) { res.push({name, searchWords: matched}); } return res; },[]) console.log(result);

It is because, how indexOf works, with array and strings .这是因为indexOf如何使用arraystrings工作。

let's say syntax of indexOf is假设 indexOf 的语法

operatedItem.indexOf(searchedItem);

Here, in your case在这里,在你的情况下

{
   name:'bb',
   searchWords:['bb','bc','de']
}

name is a string ,名称是一个字符串

and searchWords is an array .并且searchWords 是一个数组

When you perform:当你执行:

name.indexOf("b"); name.indexOf("b"); //0 //0

name.indexOf("bb"); name.indexOf("bb"); //0 //0

name.indexOf("a"); name.indexOf("a"); //-1 //-1

It will check if the searchedItem exists anywhere in operatedItem .它将检查searchedItem是否存在于operatedItem中的任何位置。

 let str = "aa ab a bb"; console.log(str.indexOf("a")); //0 console.log(str.indexOf("aa")); //0 console.log(str.indexOf("ab")); //3 console.log(str.indexOf("b")); //4 console.log(str.indexOf("c")); //-1 console.log(str.indexOf("aaa")); //-1

And when indexOf is used with array ,indexOf 与 array 一起使用时

it checks if a searchedItem exists in the operatedItem array, it will not go for substring search.它检查operatedItem项数组中是否存在searchedItem它不会 go 用于 substring 搜索。

 let arr = ["aa", "ab", "a", "bb"]; console.log(arr.indexOf("a")); //2 console.log(arr.indexOf("aa")); //0 console.log(arr.indexOf("ab")); //1 console.log(arr.indexOf("b")); //-1 console.log(arr.indexOf("c")); //-1 console.log(arr.indexOf("aaa")); //-1

The issue with the code is that its trying to find if the array contains a word when you use indexOf.代码的问题在于,当您使用 indexOf 时,它会尝试查找数组是否包含单词。 Eg: When you search for 'a', the code checks is there is any word 'a' in the array and not any word containing letter 'a'.例如:当您搜索“a”时,代码会检查数组中是否有任何单词“a”,而不是任何包含字母“a”的单词。

You need to change the JS part to:您需要将 JS 部分更改为:

Js JS

 const list = [{ name: 'aa', searchWords: ['aa', 'ab', 'bc'] }, { name: 'bb', searchWords: ['bb', 'bc', 'de'] } ]; let searchWord = "a"; const filterItems = list.filter( (item) => item.searchWords.filter(word => word.includes(searchWord)).length > 0 ); document.getElementById('result').innerHTML = JSON.stringify(filterItems);
 <p id="result"> </>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM