JavaScript中按指定行长度将一维数组转换为二维数组
数组分割解决方案
问题说明
已有一维对象数组,已完成复制并按y属性升序排序,需根据指定的行长度数组(如row_length = [5, 5, 5, 2, 4]),将其分割为对应长度的二维数组,每个子数组包含原数组中的对象元素。
实现代码
方案一:不修改原排序数组(推荐)
该方案使用slice截取子数组,不会改变已排序的points数组,保持数据完整性:
const Darray = [{x: 334, y: 400.5}, {x: 237, y: 389},{x: 149, y: 387.5},{x: 55, y: 379.5},{x: 210, y: 301.5},{x: 48, y: 295.5},{x: 378.5, y: 224.5},{x: 283, y: 217.5},{x: 121.5, y: 211.5},{x: 198.5, y: 211.5},{x: 42.5, y: 201},{x: 33, y: 134},{x: 364, y: 142},{x: 268.5, y: 137},{x: 192, y: 136.5},{x: 106, y: 131.5},{x: 263.5, y: 68},{x: 182.5, y: 63.5},{x: 102.5, y: 61.5},{x: 344.5, y: 65.5},{x: 32, y: 52}]; // 复制并按y升序排序 const points = Darray.slice().sort((a, b) => a.y - b.y); const row_length = [5, 5, 5, 2, 4]; let startIndex = 0; const new_Darray = row_length.map(len => { const endIndex = startIndex + len; // 截取从startIndex到endIndex的元素(不包含endIndex) const subArray = points.slice(startIndex, endIndex); startIndex = endIndex; return subArray; }); console.log(new_Darray);
方案二:修改原排序数组
该方案使用splice直接从原排序数组中提取元素,会修改points数组:
const Darray = [{x: 334, y: 400.5}, {x: 237, y: 389},{x: 149, y: 387.5},{x: 55, y: 379.5},{x: 210, y: 301.5},{x: 48, y: 295.5},{x: 378.5, y: 224.5},{x: 283, y: 217.5},{x: 121.5, y: 211.5},{x: 198.5, y: 211.5},{x: 42.5, y: 201},{x: 33, y: 134},{x: 364, y: 142},{x: 268.5, y: 137},{x: 192, y: 136.5},{x: 106, y: 131.5},{x: 263.5, y: 68},{x: 182.5, y: 63.5},{x: 102.5, y: 61.5},{x: 344.5, y: 65.5},{x: 32, y: 52}]; const points = Darray.slice().sort((a, b) => a.y - b.y); const row_length = [5, 5, 5, 2, 4]; const new_Darray = row_length.reduce((result, len) => { // 从数组开头截取len个元素,原数组会被修改 result.push(points.splice(0, len)); return result; }, []); console.log(new_Darray);
逻辑说明
- 方案一通过
map遍历行长度数组,维护一个起始索引startIndex,每次计算结束索引后用slice截取对应区间的元素,更新起始索引后进入下一轮。这种方式不会改变原排序数组,适合后续还需要使用points的场景。 - 方案二通过
reduce累加结果数组,每次用splice从points开头取出指定长度的元素,添加到结果中。注意splice会直接修改原数组,执行后points会变为空数组。
内容的提问来源于stack exchange,提问作者Js541
相关产品推荐
相关产品推荐

