
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Consecutive Elements Sum in 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]
Example
The code for this will be −
const arr11 = [1, 1, 2, 7, 4, 5, 6, 7, 8, 9]; const consecutiveSum = arr => { const res = []; for(let i = 0; i < arr.length; i += 2){ res.push(arr[i] + (arr[i+1] || 0)); }; return res; }; console.log(conseutiveSum(arr1));
Output
The output in the console −
[ 2, 9, 9, 13, 17 ]
Advertisements