Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Sum of consecutive numbers in JavaScript
Let's say, we have to write a function that takes in an array and returns another array in which the consecutive similar numbers are added up together.
For example ?
const array = [1, 5, 5, 5, 8, 8, 9, 1, 4, 4, 2];
console.log("Original array:", array);
Original array: [ 1, 5, 5, 5, 8, 8, 9, 1, 4, 4, 2 ]
The output should be ?
[1, 15, 16, 9, 1, 8, 2]
All consecutive 5s added up to 15, then 2 consecutive 8s added up to 16 similarly 4s added up to 8.
Using Array.reduce() Method
We will use the Array.prototype.reduce() method to reduce the original array and simultaneously construct a new one.
const array = [1, 5, 5, 5, 8, 8, 9, 1, 4, 4, 2];
const sumConsecutive = (array) => {
return array.reduce((acc, val) => {
if (acc.last === val) {
acc.arr[acc.arr.length - 1] += val;
} else {
acc.arr.push(val);
acc.last = val;
}
return acc;
}, { arr: [], last: undefined }).arr;
};
console.log(sumConsecutive(array));
[ 1, 15, 16, 9, 1, 8, 2 ]
How It Works
The function uses an accumulator object with two properties:
- arr: Stores the result array
- last: Tracks the previous element
For each element, if it matches the last seen value, we add it to the most recent sum. Otherwise, we start a new group.
Alternative Approach Using For Loop
const sumConsecutiveLoop = (array) => {
if (array.length === 0) return [];
const result = [];
let currentSum = array[0];
for (let i = 1; i < array.length; i++) {
if (array[i] === array[i - 1]) {
currentSum += array[i];
} else {
result.push(currentSum);
currentSum = array[i];
}
}
result.push(currentSum); // Add the last sum
return result;
};
const testArray = [1, 5, 5, 5, 8, 8, 9, 1, 4, 4, 2];
console.log(sumConsecutiveLoop(testArray));
[ 1, 15, 16, 9, 1, 8, 2 ]
Conclusion
Both approaches effectively sum consecutive duplicate numbers. The reduce method is more functional, while the for loop approach is more straightforward and potentially easier to understand.
