- 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
From an array of arrays, return an array where each item is the sum of all the items in the corresponding subarray in JavaScript
Given an array of arrays, each of which contains a set of numbers. We have to write a function that returns an array where each item is the sum of all the items in the corresponding subarray.
For example −
If the input array is −
const numbers = [ [1, 2, 3, 4], [5, 6, 7], [8, 9, 10, 11, 12] ];
Then output of our function should be −
const output = [10, 18, 50];
So, let’s write the code for this function −
Example
const numbers = [ [1, 2, 3, 4], [5, 6, 7], [8, 9, 10, 11, 12] ]; const sum = arr => arr.reduce((acc, val) => acc+val); const sumSubArray = arr => { return arr.reduce((acc, val) => { const s = sum(val); acc.push(s); return acc; }, []); }; console.log(sumSubArray(numbers));
Output
The output in the console will be −
[ 10, 18, 50 ]
Advertisements