將原始陣列拆分成指定長度的二維陣列
list => source array
columns => columns number
targetList => two-dimensional array
const list = [1,2,3,4,5,6,7,8,9,10]
const columns = 4;
const targetList = [ [1,2,3], [4,5,6], [7,8,9], [10] ];
const columns = 5;
const targetList = [ [1,2], [3,4], [5,6], [7,8], [9,10] ];
const columns = 6;
const targetList = [ [1,2], [3,4], [5,6], [7,8], [9], [10] ];
const list = [1,2,3,4,5,6]
const columns = 4;
const targetList = [ [1,2], [3,4], [5], [6] ];
const list = [1,2,3,4]
const columns = 5;
const targetList = [ [1], [2], [3], [4] ];
uj5u.com熱心網友回復:
您可以使用Array.prototype.reduce并使用以下條件來解決問題:
如果要推送的剩余項等于要創建的剩余行,則開始添加長度為的行
1。如果當前沒有行或最后一行已填滿,即不能在最后一行添加更多列,則使用當前專案添加新行。
最后,如果最后一行仍有空間容納更多列,則將當前專案推到最后一行
const transform = (list, rows) =>
list.reduce((t, l, i) => {
if (list.length - i === rows - t.length) {
t.push([l]);
} else if (!t.length || t.at(-1).length >= Math.ceil(list.length / rows)) {
t.push([l]);
} else {
t.at(-1).push(l);
}
return t;
}, []);
console.log(transform([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 4));
console.log(transform([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 5));
console.log(transform([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 6));
console.log(transform([1, 2, 3, 4, 5, 6], 4));
console.log(transform([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 4));
console.log(transform([1, 2, 3, 4], 5));
其他相關檔案:
- Array.prototype.at
- Array.prototype.push
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/481254.html
標籤:javascript 爪哇 数组
