I have this array [2, 1, 2, 1, 1, 1, 1, 1]
I want if the sum of the values exceed four, it's make a new array in array.
I want a result like that: [[2,1],[2,1,1],[1,1,1]]
You could use Array#reduce and use it for adding the values of the last inserted array and for the whole result array.
The main part of the algorithm is this line
!i || r[r.length - 1].reduce(add, 0) + a > 4 ?
r.push([a]) :
r[r.length - 1].push(a);
In it, a check takes place, if i is zero (at start) or if the sum of the last array of the result is in sum with the actual item greater than 4, then a new array with the actual value is added. If not, then the element is pushed to the last array.
var data = [2, 1, 2, 1, 1, 1, 1, 1],
add = function (a, b) { return a + b; },
result = data.reduce(function (r, a, i) {
!i || r[r.length - 1].reduce(add, 0) + a > 4 ? r.push([a]) : r[r.length - 1].push(a);
return r;
}, []);
console.log(result);
You can loop through the array and build a new one, if the sum exceed 4 push the previous array into the result like:
var myArr = [2, 1, 2, 1, 1, 1, 1, 1];
var newArr = [];
var newInner = [];
for (var i = 0; i < myArr.length; i++) {
if (summArr(newInner) + myArr[i] > 4) {
newArr.push(newInner);
newInner = [];
}
newInner.push(myArr[i]);
if (i==myArr.length-1) newArr.push(newInner);
}
function summArr(arr) {
return arr.reduce(add, 0);
function add(a, b) {
return a + b;
}
}