0

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]]

1
  • 3
    i dont get the logical rule.. Commented Jul 6, 2016 at 8:14

3 Answers 3

2

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);

Sign up to request clarification or add additional context in comments.

1 Comment

Wow, I see your solution, very elegant +1
0

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;
  }
}

Demo: https://jsfiddle.net/q0ps7960/

Comments

0

for simple way...

var array1 = [2, 1, 2, 1, 1, 1, 1, 1];
	var tmp=[];
	var output=[];
	var sum=0;
		for(var i=0; i<array1.length; i++){
			sum +=array1[i];
			if(sum<=4){
				tmp.push(array1[i]);
			}else{
				output.push(tmp);
				sum =array1[i];
				tmp=[array1[i]];
			}
		}
		output.push(tmp);
console.log(output);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.