[我擁有的]
具有 n 個元素的扁平或一維陣列,例如具有以下 12 個專案的陣列 A。
const A = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
[我想做的事]
將 A整形為多維陣列 B,其形狀由陣列 C 確定,陣列 C 可能因其他條件而異。
// scenario 1
const C = [ 2, 3, 2 ]
// reshaped A should be:
// [[[1, 2],
// [3, 4],
// [5, 6]],
// [[7, 8],
// [9, 10],
// [11, 12]]]
// scenario 2
const C = [ 3, 4 ]
// reshaped A should be:
// [[1, 2, 3, 4],
// [5, 6, 7, 8],
// [9, 10, 11, 12]]
// and so on...
[我嘗試過的]
我找到了以下參考文獻,它可以通過任意行數將展平的陣列解平為二維陣列:將陣列解平為四組 [關閉]
function arrayUnflatten (_flattenedArray, _numRows) {
const len = _flattenedArray.length;
const unflattenedArray = [];
while (_flattenedArray.length > 0) unflattenedArray.push(_flattenedArray.splice(0, _numRows));
return unflattenedArray;
}
[我還沒想明白的]
我還沒有想出如何制作“動態嵌套 for 回圈”,或者需要某種遞回,將一維陣列重塑為由另一個陣列確定的任意形狀的多維陣列。
幫助表示贊賞。
uj5u.com熱心網友回復:
這是我的解決方案:
const A = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
const C = [3, 4];
function unflattenArray(arr, dim) {
let elemIndex = 0;
if (!dim || !arr) return [];
function _nest(dimIndex) {
let result = [];
if (dimIndex === dim.length - 1) {
result = result.concat(arr.slice(elemIndex, elemIndex dim[dimIndex]));
elemIndex = dim[dimIndex];
} else {
for (let i = 0; i < dim[dimIndex]; i ) {
result.push(_nest(dimIndex 1));
}
}
return result;
}
return _nest(0);
}
console.log(unflattenArray(A, C));
_nest是一個遞回函式。由于關閉,它可以訪問elemIndex,arr和dim。elemIndex指的是從 array 讀取的當前元素的索引arr。
_nest獲取當前維度的索引:dimIndex。它首先用 0 呼叫。
- 如果
dimIndex參考dim陣列中的最后一個維度,則必須回傳相應大小的一維陣列。這是遞回的基本條件。它回傳一個arr從 開始的切片elemIndex,大小為dim[dimIndex]。 - 否則,它會呼叫
_nest下一個維度,dim[dimIndex]時間。例如,當dimIndex 為0 時,即大小為3 => 我們需要3 個陣列,因此我們呼叫_nest三次,每個陣列的大小在上例中為4。
uj5u.com熱心網友回復:
遞回是一種函式式遺產,因此以函式式風格使用它會產生最好的結果。這意味著避免諸如突變、變數重新分配和其他副作用之類的事情。
此外,您的輸入被過度指定。不需要最后一個數字,因為可以在沒有它的情況下確定輸出 -
function nest (t, q) {
if (q.length < 1)
return t
else
return cut(t, t.length/q[0]).map(r => nest(r, q.slice(1)))
}
function cut (t, n) {
if (n >= t.length)
return [t]
else
return [t.slice(0,n), ...cut(t.slice(n), n)]
}
const A = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
console.log(JSON.stringify(nest(A, [3])))
console.log(JSON.stringify(nest(A, [2,3])))
[[1,2,3,4],
[5,6,7,8],
[9,10,11,12]]
[[[1,2],
[3,4],
[5,6]],
[[7,8],
[9,10],
[11,12]]]
?? 當q輸入不是因素時,預期會出現意外的輸出t.length
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/328812.html
上一篇:計算字串中空格和句點數的遞回方法
