- 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
Addition multiplication ladder in an array in JavaScript
We are required to write a JavaScript function that takes in an array of numbers and returns the alternative multiplicative sum of the elements.
For example: If the array is −
const arr = [1, 2, 3, 4, 5, 6, 7];
Then the output should be calculated like this −
1*2+3*4+5*6+7 2+12+30+7
And the output should be −
51
Let’s write the code for this function −
Example
The code for this will be −
const arr = [1, 2, 3, 4, 5, 6, 7]; const alternateOperation = arr => { const productArr = arr.reduce((acc, val, ind) => { if(ind % 2 === 1){ return acc; }; acc.push(val * (arr[ind + 1] || 1)); return acc; }, []); return productArr.reduce((acc, val) => acc + val); }; console.log(alternateOperation(arr));
Output
The output in the console −
51
Advertisements