Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
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 ] ]
Advertisements