javascript - 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
任何人都可以就如何进行提供任何建议吗?
解决方案
尝试这个。遍历避难所,如果可以,将其添加到当前避难所列表中。如果没有,保存当前的避难所名册并开始一个新的。在循环之后,确保保存当前正在写入的名册
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);
推荐阅读
- c++ - 在 boost r-tree 中存储或访问对象
- c - 如何在流(FILE)中实现“文件位置”?
- mysql - MySql 在单个查询中进行多项选择
- swift - 将按钮放在节页眉/页脚上时,iOS 14 上出现奇怪的 UI 渲染问题
- php - 正则表达式检测尾随逗号和/或空格分隔的数字
- rollupjs - Rollup:使模块全局可访问,无需导入
- javascript - 在另一个选择之后选择和取消选择行 - ReactJS Hooks
- c# - 使用不同版本名称空间序列化/反序列化 XSD 的方法?
- jenkins-pipeline - 通过 groovy 脚本创建 pipelineJob 环境变量的问题
- jsf - 方法完成过程后更改 Primefaces 命令按钮禁用状态