如何在JavaScript中将扁平化数组按任意形状重塑为多维数组
函数实现
function reshapeArray(flattened, shape) { // 合法性校验:判断原数组长度是否和目标shape总长度匹配 const totalLength = shape.reduce((pre, cur) => pre * cur, 1); if (flattened.length !== totalLength) { throw new Error(`长度不匹配:原数组长度为 ${flattened.length},目标shape要求长度为 ${totalLength}`); } // 拷贝原数组避免修改源数据 const source = [...flattened]; function recursiveSplit(currentShape) { if (currentShape.length === 1) { return source.splice(0, currentShape[0]); } const dim = currentShape[0]; const restShape = currentShape.slice(1); const res = []; for (let i = 0; i < dim; i++) { res.push(recursiveSplit(restShape)); } return res; } return recursiveSplit(shape); }
使用示例
const A = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]; // 场景1 const C1 = [2, 3, 2]; console.log(reshapeArray(A, C1)); // 输出:[[[1, 2], [3, 4], [5, 6]], [[7, 8], [9, 10], [11, 12]]] // 场景2 const C2 = [3, 4]; console.log(reshapeArray(A, C2)); // 输出:[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
说明
- 递归实现天然支持任意长度的shape配置,不管是2维、3维还是更高维度都可以自动生成对应的嵌套数组,不需要手动调整循环嵌套层数。
- 函数内部会先做长度合法性校验,避免拆分异常,同时拷贝了原数组,不会修改传入的原始一维数组。
内容的提问来源于stack exchange,提问作者oat
相关产品推荐
相关产品推荐

