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
Selected Reading
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 < arr.length; i += 2){
res.push(arr[i] + (arr[i+1] || 0));
};
return res;
};
console.log(doubleSum(arrayOne));
Output
The output in the console will be −
[ 1, 5, 9, 13, 17 ]
Advertisements
