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
Add two consecutive elements from the original array and display the result in a new array with 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 arrayOne = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
Then the output should be:
const newArrayOne = [1, 5, 9, 13, 17]
Let's write the code for this function:
Example
const arrayOne = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
const doubleSum = arr => {
const res = [];
for(let i = 0; i
Output
The output in the console will be:
[ 1, 5, 9, 13, 17 ]
How It Works
The function works by iterating through the array with a step of 2 (i += 2). For each iteration, it adds the current element arr[i] to the next element arr[i+1]. The || 0 ensures that if there's no next element (for odd-length arrays), it adds 0 instead of undefined.
Handling Odd-Length Arrays
const oddArray = [1, 2, 3, 4, 5];
console.log(doubleSum(oddArray));
[ 3, 7, 5 ]
In this case, the last element (5) has no pair, so it's added to 0, resulting in 5.
Conclusion
This approach efficiently creates a new array by summing consecutive pairs of elements. The loop increment of 2 ensures we process every pair, while the || 0 handles odd-length arrays gracefully.
