You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript:基于容量条件创建对象的二维数组

Solution for Animal Shelter Grouping Problem

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

  1. Initialization: We set up currentShelter to hold the current group of regions, and currentTotal to track their combined animal count.
  2. Iteration: For each region entry:
    • If adding its quantity to currentTotal doesn't exceed 50, we add it to currentShelter and update the total.
    • If it does exceed, we push the full currentShelter to array2, then start fresh with a new shelter containing just this entry.
  3. Final Step: After the loop ends, there will always be an unfinished currentShelter left (even if it's just one entry), so we push that to array2 too.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 09:08:38