Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Split array into groups (array of arrays) based on equal values

I'm trying to do this exercise:

The challenge is to implement a function which adds all together all the consecutive numbers in an array and pushes them into a new array. example: sumConsecutives([1,1,2,1,1,1,1,2,1,1,1]); // -> [2,2,4,2,3]

My idea is to split the array into an array of arrays. So for the above example: [[1,1],[2],[1,1,1,1],[2],[1,1,1]] then go through and reduce them.

I've tried with a while loop and push into a temp variable which then gets pushed if the next number is not the same, to no avail.

Any ideas on how to achieve this?

like image 609
Apswak Avatar asked Sep 27 '26 00:09

Apswak


1 Answers

The easiest approach I could think of... (without map/reduce, though)

var sumConsecutives = function(arr) {
var newArr = [];
var prev = arr[0];
var sum = arr[0];

for (var i=1; i<arr.length; i++){
	if (arr[i] !== prev) {
		newArr[newArr.length] = sum;
		sum = 0;
	}
	sum += arr[i];
	prev = arr[i];
}

// Add last sum
newArr[newArr.length] = sum;

return newArr;
};

console.log ( sumConsecutives([1,1,2,1,1,1,1,2,1,1,1]) );
	
like image 137
lpg Avatar answered Sep 29 '26 14:09

lpg