igaman
igaman

Reputation: 59

How to convert an array in an complex array

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

Upvotes: 0

Views: 63

Answers (3)

Nina Scholz
Nina Scholz

Reputation: 386868

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

Upvotes: 2

C.Raf.T
C.Raf.T

Reputation: 383

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

Upvotes: 0

Irvin Dominin
Irvin Dominin

Reputation: 30993

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/

Upvotes: 0

Related Questions