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?
Using the Formula(n / 2)(first number + last number) = sum, where n is the number of integers.
– The sum of any two consecutive numbers is always odd. Example, 4 + 5 = 9; –8 + (–7) = –15.
The sum of 7 consecutive natural numbers is 70 .
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;
};
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