如何在值为二维数组的JavaScript对象中查找匹配指定数组的键
JavaScript二维数组属性检索实现方案
需求说明
实现一个检索函数,接收一个一维数组作为参数,从属性值为二维数组的对象中,找出所有属性值包含该入参数组的属性,返回匹配的属性名组成的数组。
示例参考
给定测试对象:
var items = { "bob":[[0,0,0],[0,0,1],[0,1,0]], "joe":[[0,0,0],[1,1,1],[0,1,0]], "ike":[[0,0,0],[0,0,2],[1,1,1]] }
预期查询效果:
- 传入
[0,0,0]返回["bob","joe","ike"] - 传入
[0,1,0]返回["bob","joe"] - 传入
[1,1,1]返回["joe","ike"] - 传入
[0,0,2]返回["ike"]
实现方案
方案1:单次查询通用实现
适合只需要少量查询的场景,不需要额外空间预存索引,实现逻辑简单:
// 辅助函数:判断两个一维数组内容是否完全一致 function arraysEqual(a, b) { if (a.length !== b.length) return false; for (let i = 0; i < a.length; i++) { if (a[i] !== b[i]) return false; } return true; } // 检索函数 function findMatchingKeys(targetArr, searchObj) { const matchedKeys = []; for (const key in searchObj) { // 遍历当前属性的二维数组,判断是否存在匹配项 const isMatch = searchObj[key].some(subArr => arraysEqual(subArr, targetArr)); if (isMatch) matchedKeys.push(key); } return matchedKeys; }
使用示例:
console.log(findMatchingKeys([0,1,0], items)) // 输出 ["bob","joe"]
方案2:高频率查询优化方案
如果需要对同一个对象进行多次查询,推荐提前构建序列化索引,索引仅需构建一次,后续查询时间复杂度可降至O(1),检索效率大幅提升:
// 预构建索引函数,仅需执行一次 function buildSearchIndex(searchObj) { const indexMap = new Map(); for (const key in searchObj) { searchObj[key].forEach(subArr => { // 序列化子数组作为索引的键,这里用逗号拼接,也可根据场景替换为JSON.stringify const indexKey = subArr.join(','); if (!indexMap.has(indexKey)) { indexMap.set(indexKey, []); } // 避免同一个属性名重复添加 const currentKeys = indexMap.get(indexKey); if (!currentKeys.includes(key)) { currentKeys.push(key); } }) } return indexMap; } // 构建索引 const itemsIndex = buildSearchIndex(items); // 快速检索函数 function fastFindMatchingKeys(targetArr, indexMap) { const indexKey = targetArr.join(','); return indexMap.get(indexKey) || []; }
使用示例:
console.log(fastFindMatchingKeys([1,1,1], itemsIndex)) // 输出 ["joe","ike"]
内容的提问来源于stack exchange,提问作者Josh Stovall
相关产品推荐
相关产品推荐

