首页 > 解决方案 > JavaScript:根据条件创建二维对象数组

问题描述

我正在从事一个涉及二维对象数组的项目。我一直在努力试图找出这个答案一段时间,我对如何解决它有一些想法,但我有点难过。

假设里面有动物收容所City A,每个收容所可以容纳 50 只动物。动物从该州的不同地方进来,但一个地方的动物数量永远不会超过 50 只。这里是动物进来的一个例子。

let animal_shelter_capacity =< 50;

let array 1 = [
  { "region": "NE", quantity: 25 },
  { "region": "NW", quantity: 21 },
  { "region": "SE", quantity: 43 },
  { "region": "SW", quantity: 18 },
  { "region": "Central", quantity: 20} 
]

在这个例子中,来自NE(25) 和NW(21) 的动物将去一个收容所(总共 46 只动物),来自SE(43) 的动物将去另一个收容所(总共 43 只动物),来自SW(18 ) 的动物) 和Central(20) 将去第三个庇护所(总共 38 只动物)。一个收容所里的动物数量永远不能超过 50 只。

所以,我需要生成一个如下所示的数组:

let array2 = [ 
  [ { "region": "NE", quantity: 25 }, { "region": "NW", quantity: 21 }],
  [ { "region": "SE", quantity: 43 } ],
  [ { "region": "SW", quantity: 18 }, { "region": "Central", quantity: 20} ] 
]

我可以循环array1使用 using forEach,但是当涉及到添加直到达到某个值,然后创建一个新的数组数组时,我对如何继续执行此操作有点困惑。

这是我到目前为止所拥有的:

let array2 = [] //instantiate array

array1.forEach(function(element, index, array)
{
    let sum = 0;
    let capacity = 50;

    for (let j = 0; j < array1.length; j++)
    {
        sum += array1[j].quantity;
        if (sum >= capacity)
        {
            //create the new array consisting of the regions, push it into the larger array2
        }
    }
})

我不确定如何继续这样做。我知道我需要执行以下操作:

1. find a way to cut off the addition sequence once the quantity reaches 50
2. reset the sequence 
3. form the new arrays and push them into a larger array

任何人都可以就如何进行提供任何建议吗?

标签: javascriptarraysloopsobjectforeach

解决方案


尝试这个。遍历避难所,如果可以,将其添加到当前避难所列表中。如果没有,保存当前的避难所名册并开始一个新的。在循环之后,确保保存当前正在写入的名册

const locations = [{
    "region": "NE",
    "quantity": 25
  },
  {
    "region": "NW",
    "quantity": 21
  },
  {
    "region": "SE",
    "quantity": 43
  },
  {
    "region": "SW",
    "quantity": 18
  },
  {
    "region": "Central",
    "quantity": 20
  }
]

const shelterRoster = [];
const capacity = 50;
let count = 0;
for (let location of locations) {
  let shelter = shelterRoster[shelterRoster.length - 1];

  if (!shelter || count + location.quantity > capacity) {
    shelterRoster.push([location]);
    count = 0;
  } else {
    shelter.push(location);
  }

  count += location.quantity
}

console.log(shelterRoster);


推荐阅读