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?
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?
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>'); 
    
    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;
};
 
    
    We could solve this using iteration. The code would look something like this
var numbers = [1, 2, 2, 2, 5, 7];
var newNumbers = [];
for (var i = 0; i < numbers.length; i++) {
    numbers = numbers.filter(function(num) {
        return num;
    });
Here we are removing elements that are undefined which will be deleted, so we don't repeat groups.
    var number = numbers[i];
    var nextUnique = numbers.find(function(num) {
        return num != number
    });
    var numbersToFind = numbers.indexOf(nextUnique) - i;
Above, we are searching for the number of numbers in a repeated group.
    if (numbersToFind > 0) {
        var numbersGroup = numbers.slice(i, i + numbersToFind + 1);
        var sumNumbers = numbersGroup.reduce(function(num1, num2) {
            return num1 + num2;
        });
        newNumbers.push(sumNumbers);
        delete numbers[i];
    }
We use the reduce function to sum up the numbers that are identical. We will then delete the original number to prevent duplicates in our newNumbers array.
    else {
        newNumbers.push(numbers[i]);
   }
}
Otherwise, the new number will simply be the number at the index.
alert(newNumbers);
Browser Compatibility
It should be noted that the array.prototype.find function is an experimental technology and is not yet available on Internet Explorer or Opera.
