
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
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 ]
- Related Articles
- Adding an element at a given position of the array in Javascript
- Adding an element at the end of the array in Javascript
- Adding an element at the start of the array in Javascript
- Extract unique values from an array - JavaScript
- Adding an element in an array using Javascript
- Select random values from an array in JavaScript?
- Joining two strings with two words at a time - JavaScript
- Iterating through an array, adding occurrences of a true in JavaScript
- How to remove false values from an array in JavaScript?
- Get the max n values from an array in JavaScript
- Retrieve key and values from object in an array JavaScript
- How to remove falsy values from an array in JavaScript?
- Fetch alternative even values from a JavaScript array?
- Find unique and biggest string values from an array in JavaScript
- JavaScript: How to filter out Non-Unique Values from an Array?

Advertisements