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?
Share Improve this question edited Feb 20, 2020 at 9:42 Penny Liu 17.5k5 gold badges86 silver badges108 bronze badges asked Jan 26, 2016 at 19:32 ArnoldBArnoldB 1653 silver badges10 bronze badges 2- Apply code on stackoverflow./a/9229821/1169519 – Teemu Commented Jan 26, 2016 at 19:36
- 1 Oh, in meantime you removed your original question! – i-blis Commented Jan 26, 2016 at 20:42
4 Answers
Reset to default 3You 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 use lodash and want a functional variant, you could also do:
_.chain([1,2,2,2,5,7]).groupBy(_.identity).map(_.sum).value()
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.