Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum of consecutive numbers JavaScript

Given an array of integers.

For example:

[1,2,2,2,5,7]

I want to output any groups of consecutive identical numbers with their sum.

The output should be:

[1,6,5,7]

Any thoughts on how to do this?

like image 511
ArnoldB Avatar asked Jan 26 '16 19:01

ArnoldB


People also ask

How do you find the sum of consecutive numbers?

Using the Formula(n / 2)(first number + last number) = sum, where n is the number of integers.

What is the sum of consecutive?

– The sum of any two consecutive numbers is always odd. Example, 4 + 5 = 9; –8 + (–7) = –15.

What is the sum of 7 consecutive numbers?

The sum of 7 consecutive natural numbers is 70 .


2 Answers

You can use Array.prototype.reduce() with a temporary object.

var array = [1, 2, 2, 2, 5, 7],
    result = array.reduce(function (r, a) {
        if (r.last === a) {
            r.array[r.array.length - 1] += a;
        } else {
            r.array.push(a);
            r.last = a;
        }
        return r;
    }, { array: [], last: null }).array;

document.write('<pre>' + JSON.stringify(result,0,4) + '</pre>');
like image 121
Nina Scholz Avatar answered Sep 20 '22 21:09

Nina Scholz


I solved it this way.

const sumConsecutives = (s) => {
  let result = [], temp = 0;
  for(let i = 0; i<s.length; i++) {
    if(s[i] === s[i+1]){
      temp += s[i];
    } else if(s[i] !== s[i+1]){
      result.push(temp + s[i]);
      temp = 0;
    }
  }
  return result;
};
like image 42
Kim SangHun Avatar answered Sep 19 '22 21:09

Kim SangHun