# 一个分组算法js，可以伪代码提供思路，一直在线

0

``````/*比如有这样一个数组，数组只相加<=8分组,大于8就分到下一组，

var arr = [2, 3, 4, 2, 2, 2, 3, 4];

arr=  [
[2,3],
[4,2,2],
[2,3],
[4]
]``````

0

``````function fuck(arr)
{
newArray = [[]];

foreach(a in arr):
{
if(sum(newArray.Last) + a <= 8)
{
newArray.Last.append(a);
}
else
{
nextArray = [a];
newArray.append(nextArray)
}
}
return newArray;
}``````

`````` function fuck(arr) {
var newArray = [[]];
//sum函数
function sum(arr) {
arr = arr || [];
var total = arr.reduce(function (total, item) {
}, 0);
}
arr.forEach(a => {
//变动
newArray.Last = newArray.Last || [];
if (sum(newArray.Last) + a <= 8) {
newArray.Last.push(a);
}
else {
var nextArray = [a];
newArray.push(nextArray)
}
});
return newArray;
}

var a = fuck(arr);
console.info(a);``````

@困了: 大哥，我写的是伪代码，因为我 不熟悉js，给你修改下：

``````    function fuck(arr) {
var newArray = [[]];
//sum函数
function sum(arr) {
arr = arr || [];
var total = arr.reduce(function (total, item) {
}, 0);
}
arr.forEach(a => {
//变动
newArray[newArray.length - 1] = newArray[newArray.length - 1] || [];
if (sum(newArray[newArray.length - 1]) + a <= 8) {
newArray[newArray.length - 1].push(a);
}
else {
var nextArray = [a];
newArray.push(nextArray)
}
});
return newArray;
}

var arr = [2, 3, 4, 2, 2, 2, 3, 4];
var a = fuck(arr);``````

js的数组好像没有Last属性，改改就能用了

@会长: 刚才last那个没想明白

您需要登录以后才能回答，未注册用户请先注册