- 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
Return the largest array between arrays JavaScript
We have an array of arrays that contains some numbers, we have to write a function that returns the takes in that array and returns the index of the subarray that has the maximum sum. If more than one subarray has the same maximum sum, we have to return the index of first such subarray.
Therefore, let’s write the code for this −
Example
const arr = [[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]; const findMaxSubArray = (arr) => { const add = (array) => array.reduce((acc, val) => acc+val); return arr.reduce((acc, val, ind) => { const sum = add(val); if(sum > acc.sum){ return { index: ind, sum } }; return acc; }, { index: -1, sum: -Infinity }).index; }; console.log(findMaxSubArray(arr));
Output
The output in the console will be −
3
Advertisements
To Continue Learning Please Login
Login with Google