
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Return the sum of two consecutive elements from the original 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 sum of two consecutive elements from the original array.
For example, if the input array is −
const arr = [3, 6, 3, 87, 3, 23, 2, 2, 6, 8];
Then the output should be −
const output = [9, 90, 26, 4, 14];
Example
The code for this will be −
const arr = [3, 6, 3, 87, 3, 23, 2, 2, 6, 8]; const twiceSum = arr => { const res = []; for(let i = 0; i < arr.length; i += 2){ res.push(arr[i] + (arr[i+1] || 0)); }; return res; }; console.log(twiceSum(arr));
Output
The output in the console will be −
[ 9, 90, 26, 4, 14 ]
- Related Questions & Answers
- Add two consecutive elements from the original array and display the result in a new array with JavaScript
- Consecutive elements sum array in JavaScript
- Return Top two elements from array JavaScript
- Maximum sum of n consecutive elements of array in JavaScript
- Check for Subarray in the original array with 0 sum JavaScript
- JavaScript - Constructs a new array whose elements are the difference between consecutive elements of the input array
- Finding sum of alternative elements of the array in JavaScript
- Return a subarray that contains all the element from the original array that are larger than all the elements on their right in JavaScript
- Return an array of all the indices of minimum elements in the array in JavaScript
- Alternating sum of elements of a two-dimensional array using JavaScript
- Return the floor of the array elements in Numpy
- Absolute sum of array elements - JavaScript
- Return the cumulative sum of array elements treating NaNs as zero in Python
- Sum of consecutive numbers in JavaScript
- Find original array from encrypted array (An array of sums of other elements) using C++.
Advertisements