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
Consecutive elements sum array in JavaScript
We are required to write a JavaScript function that takes in an array of Numbers and returns a new array with elements as the sum of two consecutive elements from the original array.
For example, if the input array is ?
const arr1 = [1, 1, 2, 7, 4, 5, 6, 7, 8, 9];
Then the output should be ?
const output = [2, 9, 9, 13, 17]
How It Works
The function pairs consecutive elements: (1+1=2), (2+7=9), (4+5=9), (6+7=13), (8+9=17). If the array has an odd length, the last element is paired with 0.
Example
The code for this will be ?
const arr1 = [1, 1, 2, 7, 4, 5, 6, 7, 8, 9];
const consecutiveSum = arr => {
const res = [];
for(let i = 0; i
Output
The output in the console ?
[ 2, 9, 9, 13, 17 ]
Handling Odd-Length Arrays
When the array has an odd number of elements, the last element gets paired with 0:
const oddArray = [1, 2, 3, 4, 5];
console.log(consecutiveSum(oddArray));
[ 3, 7, 5 ]
Alternative Approach Using map()
Here's a more functional programming approach:
const consecutiveSumMap = arr => {
return arr.filter((_, i) => i % 2 === 0)
.map((val, i) => val + (arr[i * 2 + 1] || 0));
};
const arr2 = [2, 4, 6, 8, 10];
console.log(consecutiveSumMap(arr2));
[ 6, 14, 10 ]
Conclusion
Both approaches effectively sum consecutive pairs in an array. The for-loop method is more straightforward, while the map() approach follows functional programming principles. Choose based on your coding style preference.
