3

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?

9
  • 4
    You want us to do your homework? And please, share your code. We will help you fix bugs but we are not your code factory. Commented Aug 9, 2016 at 8:42
  • What have you achieved so far? Please paste your code snippet, if you have one, to help you improve it. Commented Aug 9, 2016 at 8:44
  • please bring the code into the studio Commented Aug 9, 2016 at 8:51
  • @Randy No. I asked for ideas on 'how to achieve this'. Did I ask you to write it out for me? Either way, code incoming Commented Aug 9, 2016 at 8:52
  • 2
    var reducer = a => a.reduce((p,c,i,a) => (i === 0 ? p[0] = c : c == a[i-1] ? p[p.length-1] += c : p[p.length] = c,p),[]) Commented Aug 9, 2016 at 8:54

7 Answers 7

3

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

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

Comments

2

You can use a one step reduce approach:

const sumConsecutives = ar =>
ar.reduce((ac, x, i) => {
  if ( i !== 0 && ar[i-1] === x)
    ac[ac.length -1] += x;
  else 
    ac.push(x);
    
  return ac;
 }, [])


var r = sumConsecutives([1,1,2,1,1,1,1,2,1,1,1]); // -> [2,2,4,2,3]

console.log(r)

1 Comment

@Kreitzo I didn't actually understand if you want to count the repeated instances of the duplicate following numbers or use their sum, if you want to change current behaviour look on line 4
1

I liked the challange so I made it in a two-step function you thought was useful.

  • The first reduce creates the array of arrays

  • The second reduce sums them up.

It is not the shortest code, but I hope the most understandable.

const arr = [1,1,2,1,1,1,1,2,1,1,1];
let currentNumber = undefined;
let currentTempArr = [];

let newArr = arr.reduce((tempArr, value) => {
  // check if current number is set
  if(currentNumber == undefined) currentNumber = value;
  
  // if current number then push to temp array
  if(currentNumber == value)
    currentTempArr.push(value);
  // else just create a new array and push the old one into the parent array
  else {
    tempArr.push(currentTempArr);
    currentTempArr = [];
    currentNumber = value;
    currentTempArr.push(value);
  }
  
  // return the array back to the next reduce iteration
  return tempArr;
}, []);

// push the last temp array, because the function stops before the push
newArr.push(currentTempArr);

// this build your array of arrays
console.info('The array of arrays');
console.log(newArr); // [ [1,1,1], [2], ... ]

// now sum up the sub arrays
let sumArr = newArr.reduce((tempArr, value) => {
  let sum = 0;
  
  // for every value in the array we add that to the sum
  value.forEach(val => sum += val);
  
  // add the total to the temp array
  tempArr.push(sum);
  
  // return the filled array back to the reduce function
  return tempArr;
}, []);

// the array with summed up values
console.info('see the magic happen');
console.log(sumArr);

Comments

0
function sumConsecutives(input) {
    var output = [],
        factor = 1,
        lastnr = null;

    for (var i = 0; i < input.length; i++) {
        if (i === 0) {
            lastnr = input[i];
            continue;
        }

        if (input[i] !== lastnr) {
            output.push(lastnr * factor);
            lastnr = input[i];
            factor = 1;
        } else {
            factor++;
        }

        if (i === (input.length - 1)) {
            output.push(input[i] * factor);
        }
    }
    return output;
}

var result = sumConsecutives([1,1,2,1,1,1,1,2,1,1,1]);

Comments

0

You can use array.reduce

Logic

  • Create a temp array.
  • loop over array and check if previous and current value.
  • If same, take last element of temp array and add current value to it.
  • If not, push current element to temp array

Sample

function sumConsecutives(arr) {
  var r = [];
  arr.reduce(function(p, c, i, a) {
    if (p === c) {
      r[r.length - 1] += c
    } else {
      r.push(c)
    }
    return c;
  }, 0);
  return r;
}
var a = [1, 1, 2, 1, 1, 1, 1, 2, 1, 1, 1];
console.log(sumConsecutives(a));

Comments

0

This is the easiest i could think of:

var testarr = [1,1,2,1,1,1,1,2,1,1,1];
var resultarr = [testarr[0]];
for(var i=1; i<testarr.length; i++){
	if(testarr[i-1]==testarr[i]){
		resultarr[resultarr.length - 1] += testarr[i];
	}else{
		resultarr.push(testarr[i]);
	}
}
console.log(resultarr);

Comments

0

You may also try this approach :

var source = [1,1,2,1,1,1,1,2,1,1,1];

source.reduce(function(p, c, index, arr) {                 
   if (p.length === 0 || arr[index - 1] !== c) {
       return p.concat(c);
   }
   else if (arr[index - 1] === c) {           
        p[p.length - 1] += c             
   }

   return p;
}, []);

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.