- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Adding two values at a time from an array - JavaScript
Let’s say, 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
Following is the code −
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
This will produce the following output in console −
[ 9, 90, 26, 4, 14 ]
Advertisements