- Related Questions & Answers
- Consecutive Numbers Sum in C++
- Check three consecutive numbers - JavaScript
- N consecutive odd numbers JavaScript
- Consecutive elements sum array in JavaScript
- Maximum sum of n consecutive elements of array in JavaScript
- JavaScript to check consecutive numbers in array?
- Finding three desired consecutive numbers in JavaScript
- Print all possible sums of consecutive numbers with sum N in C++
- Length of the longest possible consecutive sequence of numbers in JavaScript
- Finding lunar sum of Numbers - JavaScript
- Count ways to express a number as sum of consecutive numbers in C++
- Sum of all prime numbers in JavaScript
- Three strictly increasing numbers (consecutive or non-consecutive). in an array in JavaScript
- Squared sum of n odd numbers - JavaScript
- Count of pairs in an array that have consecutive numbers using JavaScript

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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];

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.

Therefore, let’s write the code for this function. We will use the Array.prototype.reduce() method here 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));

The output in the console will be −

[ 1, 15, 16, 9, 1, 8, 2 ]

Advertisements