Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to convert an array into a complex array JavaScript?
In JavaScript, converting a flat array into a complex nested array structure involves grouping elements based on specific conditions. A common use case is splitting an array into subarrays when the sum of consecutive elements exceeds a given threshold.
Let's say we need to write a function that takes an array of numbers and a number n, where n is the maximum sum allowed for each subarray. The function should break the array into subarrays whenever the sum of consecutive elements would exceed n.
Example Problem
Given an array and a threshold value, we want to create subarrays that don't exceed the sum limit:
// Original array const arr = [2, 1, 2, 1, 1, 1, 1, 1]; // Threshold n = 4 // Expected output: [[2, 1], [2, 1, 1], [1, 1, 1]]
Using Array.reduce() Method
The most efficient approach uses the reduce() method to build the complex array structure:
const arr = [2, 1, 2, 1, 1, 1, 1, 1];
const splitArray = (arr, num) => {
return arr.reduce((acc, val, ind) => {
let { sum, res } = acc;
// Handle first element
if (ind === 0) {
return { sum: val, res: [[val]] };
}
// Add to current subarray if sum doesn't exceed limit
if (sum + val
Split with limit 4: [ [ 2, 1 ], [ 2, 1, 1 ], [ 1, 1, 1 ] ]
Split with limit 5: [ [ 2, 1, 2 ], [ 1, 1, 1, 1, 1 ] ]
Alternative Approach Using For Loop
For better readability, you can also use a traditional for loop approach:
const splitArraySimple = (arr, limit) => {
const result = [];
let currentSubarray = [];
let currentSum = 0;
for (let i = 0; i limit && currentSubarray.length > 0) {
result.push(currentSubarray);
currentSubarray = [value];
currentSum = value;
} else {
currentSubarray.push(value);
currentSum += value;
}
}
// Don't forget the last subarray
if (currentSubarray.length > 0) {
result.push(currentSubarray);
}
return result;
};
const testArray = [3, 2, 1, 4, 1, 2];
console.log("Simple approach:", splitArraySimple(testArray, 5));
Simple approach: [ [ 3, 2 ], [ 1, 4 ], [ 1, 2 ] ]
How It Works
The algorithm maintains two key pieces of state:
- Current sum: Tracks the sum of elements in the current subarray
- Result array: Stores all completed subarrays
For each element, it checks if adding it would exceed the limit. If so, it starts a new subarray; otherwise, it adds the element to the current subarray.
Key Points
- The
reduce()method provides a functional programming approach - Always handle the first element separately to initialize the structure
- Remember to add the final subarray to the result
- The algorithm works with any numeric threshold
Conclusion
Converting arrays into complex nested structures is common in JavaScript. Using reduce() or loops with proper state management allows you to group elements based on custom conditions like sum thresholds.
