JavaScript:基于容量条件创建对象的二维数组
Hey there! Let's break down how to fix your grouping logic and get that 2D array working exactly as you need it.
First, let's spot the issues in your current code
Your current approach uses forEach with a nested for loop, which leads to re-traversing the entire array1 every time you process an element. Plus, you reset sum on each forEach iteration—so you can't track the running total for the current shelter group. That's why you're stuck on the "accumulate until capacity then reset" part.
The Right Approach
We need to track two key things as we iterate through array1:
- A current shelter group (to hold the regions we're grouping together)
- A running total of animals in that current group
For each region, we check if adding its animal count to the current total stays under the 50-capacity limit. If yes, we add it to the current group. If not, we finalize the current group, push it to array2, and start a new group with the current region.
Working Code Implementation
const shelterCapacity = 50; const array1 = [ { "region": "NE", quantity: 25 }, { "region": "NW", quantity: 21 }, { "region": "SE", quantity: 43 }, { "region": "SW", quantity: 18 }, { "region": "Central", quantity: 20} ]; const array2 = []; let currentShelter = []; let currentTotal = 0; array1.forEach(animalEntry => { // Check if adding this entry keeps us under capacity if (currentTotal + animalEntry.quantity <= shelterCapacity) { currentShelter.push(animalEntry); currentTotal += animalEntry.quantity; } else { // Push the full shelter to our result array array2.push(currentShelter); // Start a new shelter with the current entry currentShelter = [animalEntry]; currentTotal = animalEntry.quantity; } }); // Don't forget to add the last shelter (it won't be pushed in the loop!) if (currentShelter.length > 0) { array2.push(currentShelter); } console.log(array2);
Key Breakdown of the Logic
- Initialization: We set up
currentShelterto hold the current group of regions, andcurrentTotalto track their combined animal count. - Iteration: For each region entry:
- If adding its quantity to
currentTotaldoesn't exceed 50, we add it tocurrentShelterand update the total. - If it does exceed, we push the full
currentSheltertoarray2, then start fresh with a new shelter containing just this entry.
- If adding its quantity to
- Final Step: After the loop ends, there will always be an unfinished
currentShelterleft (even if it's just one entry), so we push that toarray2too.
Bonus Note
Since you mentioned every region's animal count is ≤50, we don't have to handle edge cases where a single region's quantity exceeds the shelter capacity. If that ever became a requirement, you could add a quick check to handle that scenario separately.
内容的提问来源于stack exchange,提问作者Leia_Organa

