如何获取子集合中各元素在父数组中的索引?
解决方案
先点明你原来代码里的问题:
childrenSubCollection.findIndex是用来查找当前子数组内元素的位置,但你需要的是原parent数组中的索引,这个方法用错了方向childrenSub[0]写法错误,因为childrenSub本身就是子数组里的单个对象(比如{name: 'one', id:1}),并非数组,这么写会得到undefined
高效实现(推荐)
先构建一个id到原数组索引的映射表,后续直接通过id查询索引,避免重复遍历parent数组,性能更优:
const parent = [{name: 'one', id: 1}, {name: 'two', id: 2}, {name: 'three', id: 3}, {name: 'four', id: 4}, {name: 'five', id: 5}] const childrenCollection = [[{name: 'one', id: 1}, {name: 'two', id: 2}], [{name: 'three', id: 3}, {name: 'four', id: 4}], [{name: 'five', id: 5}]] // 提前生成id到原数组索引的映射 const idToIndex = new Map(parent.map((item, index) => [item.id, index])) childrenCollection.forEach(childrenSubCollection => { // 处理子数组长度不足2的情况,避免报错 const indexOfOne = idToIndex.get(childrenSubCollection[0]?.id) const indexOfTwo = childrenSubCollection[1] ? idToIndex.get(childrenSubCollection[1].id) : undefined console.log(childrenSubCollection[0], childrenSubCollection[1], 'index', indexOfOne, indexOfTwo) })
简易实现(适合小数据量)
如果数据量不大,也可以直接用parent.findIndex逐个查找元素的原索引:
const parent = [{name: 'one', id: 1}, {name: 'two', id: 2}, {name: 'three', id: 3}, {name: 'four', id: 4}, {name: 'five', id: 5}] const childrenCollection = [[{name: 'one', id: 1}, {name: 'two', id: 2}], [{name: 'three', id: 3}, {name: 'four', id: 4}], [{name: 'five', id: 5}]] childrenCollection.forEach(childrenSubCollection => { const indexOfOne = parent.findIndex(item => item.id === childrenSubCollection[0].id) // 针对只有单个元素的子数组,做容错处理 const indexOfTwo = childrenSubCollection[1] ? parent.findIndex(item => item.id === childrenSubCollection[1].id) : undefined console.log(childrenSubCollection[0], childrenSubCollection[1], 'index', indexOfOne, indexOfTwo) })
需要注意:第三个子数组只有一个元素,直接访问childrenSubCollection[1]会得到undefined,所以要加判断避免报错。
内容的提问来源于stack exchange,提问作者dev
相关产品推荐
相关产品推荐

