如何用数组方法过滤二维字符串数组筛选含搜索词的子数组(禁用for循环)
问题解决:筛选包含指定关键词的二维数组子项
错误原因
你遇到的TypeError是因为Array.filter()方法要求传入一个回调函数作为筛选条件,而你直接把搜索字符串searchInput传了进去。JavaScript会尝试将这个字符串当作函数执行,自然就抛出了“字符串不是函数”的错误。
正确实现代码
利用filter遍历外层数组,结合includes检查每个子数组是否包含目标关键词,filter本身会返回符合条件的新数组,不需要额外声明空数组再手动push:
const booksArray = [ [ 'The City We Became', 'N. K. Jemisin', 'fantasy', 'fiction', 'afrofutursim', 'science fiction', 'sci-fi' ], [ 'The Catcher in the Rye', 'J. D. Salinger', 'fiction', 'young adult', 'YA', 'realism', 'coming of age', 'classic' ], [ 'The Hundred Thousand Kingdoms', 'N. K. Jemisin', 'fantasy', 'fiction', 'adventure', 'series' ], [ 'Sapiens: A Brief History of Humankind', 'Yuval Noah Harari', 'nonfiction', 'history', 'anthropology', 'science', 'sociology' ], [ 'Behave: The Biology of Humans at Our Best and Worst', 'Robert M. Sapolsky', 'nonfiction', 'anthropology', 'science', 'sociology', 'biology' ], [ 'The Parable of the Talents', 'Octavia Butler', 'fiction', 'dystopian', 'science fiction' ], [ '1984', 'George Orwell', 'fiction', 'dystopian', 'science fiction', 'classics', 'adult' ], [ 'Remarkably Bright Creatures', 'Shelby Van Pelt', 'fiction', 'mystery', 'magical realism' ], [ 'Crying in H Mart', 'Michelle Zauner', 'memoir', 'nonfiction', 'autobiography' ], [ 'Wild: From Lost to Found on the Pacific Crest Trail', 'Cheryl Strayed', 'nonfiction', 'memoir', 'adventure', 'travel' ] ]; const filterBooks = (searchInput) => { return booksArray.filter(book => book.includes(searchInput)); }; console.log(filterBooks('fantasy')); // 输出包含"fantasy"的两个子数组
可选优化:不区分大小写搜索
如果需要忽略大小写(比如搜索"Fantasy"或"FANTASY"也能匹配),可以将搜索词和子数组元素统一转为小写后再判断:
const filterBooks = (searchInput) => { const lowerSearchTerm = searchInput.toLowerCase(); return booksArray.filter(book => book.some(tag => tag.toLowerCase() === lowerSearchTerm) ); };
这里用some代替includes,是因为includes是严格大小写匹配,转小写后用some可以更精准地检查子数组中是否存在匹配的标签。
内容的提问来源于stack exchange,提问作者Anthony Luth Jr.
相关产品推荐
相关产品推荐

