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?
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]) );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With