- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
How to convert an array into a complex array JavaScript?
Let’s say, we are required to write a function that takes in an array of Numbers and number n, where n >= any number of the array. The function is required to break the array into subarrays if the sum of consecutive elements of the array exceeds the number n.
For example −
// if the original array is: const arr = [2, 1, 2, 1, 1, 1, 1, 1]; // and the number n is 4 // then the output array should be: const output = [ [ 2, 1 ], [ 2, 1, 1 ], [ 1, 1, 1 ] ];
Let’s write the code for this function −
Example
const arr = [2, 1, 2, 1, 1, 1, 1, 1]; const splitArray = (arr, num) => { return arr.reduce((acc, val, ind) => { let { sum, res } = acc; if(ind === 0){ return {sum: val, res:[[val]]}; }; if(sum + val <= num){ res[res.length-1].push(val); sum +=val; }else{ res.push([val]); sum = val; }; return { sum, res }; }, { sum: 0, res: [] }).res; }; console.log(splitArray(arr, 4)); console.log(splitArray(arr, 5));
Output
The output in the console will be −
[ [ 2, 1 ], [ 2, 1, 1 ], [ 1, 1, 1 ] ] [ [ 2, 1, 2 ], [ 1, 1, 1, 1, 1 ] ]
- Related Articles
- How to convert an array into JavaScript string?
- How to convert an object into an array in JavaScript?
- Convert JS array into an object - JavaScript
- How to Convert Hashtable into an Array?
- Convert array into array of subarrays - JavaScript
- How to convert a list into an array in R?
- How to convert a tuple into an array in C#?
- How to convert an array into a matrix in R?
- How to append an item into a JavaScript array?
- How to convert a JavaScript array to C# array?
- Java Program to convert a set into an Array
- Convert an array of objects into plain object in JavaScript
- How to convert a 2D array into 1D array in C#?
- How to convert array into array of objects using map() and reduce() in JavaScript
- JavaScript Convert an array to JSON

Advertisements