如何基于字符串子串高效过滤对象数组?
高效过滤包含指定姓名的对象数组
问题背景
给定对象数组:
[ { "Company-Last Name": "Alpha", "First Name": "One", "Category": "Cat" }, { "Company-Last Name": "Beta", "First Name": "Two", "Category": "Dog" }, { "Company-Last Name": "Gamma", "First Name": "Three", "Category": "Hamster" } ]
以及示例字符串:
This string is about Two Middle-name Beta
需要从数组中筛选出名(First Name)和姓(Company-Last Name)都出现在字符串中的对象,且要求处理效率能支撑大规模数组。
高效实现方案
单次查询场景
直接利用Set的O(1)查找特性,避免嵌套遍历:
// 输入数据 const people = [/* 你的对象数组 */]; const targetStr = "This string is about Two Middle-name Beta"; // 1. 将字符串拆分为小写单词集合,实现快速查找 const wordSet = new Set(targetStr.toLowerCase().split(/\s+/)); // 2. 过滤数组:检查每个对象的名和姓是否都在集合中 const matched = people.filter(person => { const firstName = person["First Name"].toLowerCase(); const lastName = person["Company-Last Name"].toLowerCase(); return wordSet.has(firstName) && wordSet.has(lastName); }); console.log(matched);
多次查询场景
如果需要用不同字符串多次查询,先预处理数组缓存小写后的姓名,避免重复计算:
// 预处理数组:缓存小写后的名和姓,仅需执行一次 const indexedPeople = people.map(p => ({ ...p, _lowerFirst: p["First Name"].toLowerCase(), _lowerLast: p["Company-Last Name"].toLowerCase() })); // 后续每次查询只需执行以下步骤 const targetStr = "This string is about Two Middle-name Beta"; const wordSet = new Set(targetStr.toLowerCase().split(/\s+/)); const matched = indexedPeople .filter(p => wordSet.has(p._lowerFirst) && wordSet.has(p._lowerLast)) .map(({ _lowerFirst, _lowerLast, ...rest }) => rest); // 移除缓存字段,还原原结构 console.log(matched);
效率说明
- 字符串转
Set的时间复杂度为O(k)(k为字符串单词数),后续单词查找是O(1) - 数组过滤的时间复杂度为O(n)(n为数组长度),远优于嵌套遍历的O(n*k),完全适配大规模数组场景
- 预处理缓存仅需执行一次,多次查询时能大幅节省重复转换大小写的开销
内容的提问来源于stack exchange,提问作者Dale M
相关产品推荐
相关产品推荐

