
- 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
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 ]
- Related Questions & Answers
- Return the sum of two consecutive elements from the original array in JavaScript
- JavaScript - Constructs a new array whose elements are the difference between consecutive elements of the input array
- Divide numbers from two columns and display result in a new column with MySQL
- How to add new array elements at the beginning of an array in JavaScript?
- Power array elements of an array with a given value and display the result in a different type in Numpy
- Return the floor of the array elements and store the result in a new location in Numpy
- Return the ceil of the array elements and store the result in a new location in Numpy
- Counting the occurrences of JavaScript array elements and put in a new 2d array
- Consecutive elements sum array in JavaScript
- How to add two arrays into a new array in JavaScript?
- Return the truncated value of the array elements and store the result in a new location in Numpy
- How to subtract elements of two arrays and store the result as a positive array in JavaScript?
- Create a new array from the masked array and return a new reference in Numpy
- Return Top two elements from array JavaScript
- Compress array to group consecutive elements JavaScript
Advertisements