在 JavaScript 中将项目数组拆分为 N 个数组
javascriptweb developmentfront end technologyobject oriented programming
我们需要编写一个 JavaScript 函数,将数字数组拆分为 N 组,这些组必须按从大到小的顺序排列。
例如,在下面的代码中,将 12 个数字的数组拆分为 5 个数组,结果应均匀拆分,从大(组)到小:
const arr = [1,2,3,4,5,6,7,8,9,10,11,12]; const output = [[1,2,3] [4,5,6] [7,8] [9,10] [11,12]];
该函数应将数组作为第一个参数,将分区数作为第二个参数。
示例
其代码为 −
const arr = [1,2,3,4,5,6,7,8,9,10,11,12];
const chunkArray = (arr = [], chunkCount) => {
const chunks = [];
while(arr.length) {
const chunkSize = Math.ceil(arr.length / chunkCount−−);
const chunk = arr.slice(0, chunkSize);
chunks.push(chunk);
arr = arr.slice(chunkSize);
};
return chunks;
};
console.log(chunkArray(arr, 5));
输出
控制台中的输出将是 −
[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8 ], [ 9, 10 ], [ 11, 12 ] ]
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

