如何根据参考数组动态拆分数组为多个块?
按指定位置拆分数组为多个块
给定待拆分的主数组 mainlist 和定义拆分位置的参考数组 fixedlist:
const mainlist = [ { label: '1' }, { label: '2' }, { label: '3' }, { label: '4' }, { label: '5' }, { label: '6' }, { label: '7' }, { label: '8' }, { label: '9' }, ] const fixedlist = [ { label: 'f1', position: 3 }, { label: 'f1', position: 5 }, ]
需要根据 fixedlist 中元素的 position 值拆分 mainlist,满足以下要求:
- 首次拆分从数组起始位置到第一个
position-1的索引,生成第一个块 - 处理相邻两个
position的间隔,按间隔长度生成对应块 - 主数组剩余未拆分的元素作为最后一个块
实现代码
function splitArrayByPositions(mainArr, fixedArr) { // 先按position升序排序,避免位置乱序导致拆分错误 const sortedPositions = fixedArr.map(item => item.position).sort((a, b) => a - b); const result = []; let startIndex = 0; sortedPositions.forEach(pos => { // 利用slice左闭右开特性,取startIndex到pos-1的元素 const chunk = mainArr.slice(startIndex, pos); chunk.length && result.push(chunk); startIndex = pos; }); // 处理剩余元素 if (startIndex < mainArr.length) { result.push(mainArr.slice(startIndex)); } return result; } // 调用示例 const splitResult = splitArrayByPositions(mainlist, fixedlist); console.log(splitResult);
代码说明
- 排序处理:提取并排序
fixedlist中的position值,确保拆分按从左到右的顺序进行,即使原参考数组位置乱序也能正常工作 - 循环拆分:遍历排序后的位置,每次从当前起始索引
startIndex到目标位置pos切片,非空块加入结果数组后更新起始索引 - 剩余元素处理:循环结束后若起始索引未到主数组末尾,将剩余部分作为最后一个块加入结果
示例输出
运行上述代码后,得到的拆分结果为:
[ [ { label: '1' }, { label: '2' }, { label: '3' } ], [ { label: '4' }, { label: '5' } ], [ { label: '6' }, { label: '7' }, { label: '8' }, { label: '9' } ] ]
内容的提问来源于stack exchange,提问作者aspirinemaga
相关产品推荐
相关产品推荐

