很难对数组进行分组。任何建议。
例如,我有一个数组var a = [10, 100, 20, 50, 20, 50, 70, 120]
并且我的最大值为150
,最小长度为3
,即每个子数组的总最大和为150,最大长度为3
任何建议使其像[[10, 100, 20], [50, 20, 50], [70], [120]]
预先感谢
const calcSum = arr => arr.reduce((s,i) => s+i,0);
function groupArray(input, maxSum, maxLen) {
const res = [[]];
let mark = 0;
input.forEach( ele => {
// if the current group has already reach maxLenght or maxSum
// then create a new group
if ( res[mark].length > (maxLen-1)
|| (calcSum(res[mark]) + ele) > maxSum ) {
res.push([ele]);
mark++;
}
// otherwise add to current grop
else {
res[mark].push(ele);
}
});
return res;
}
const input = [10, 100, 20, 50, 20, 50, 70, 120];
console.log(groupArray(input, 150, 3));
注意:由于问题没有任何其他规则,因此该函数不会对数组重新排序,也不会尝试寻找最佳的长度匹配或最佳的总和匹配。