如何创建组并根据每个组的最大值分配每个组的数量?

  • 本文关键字:分配 最大值 创建组 javascript
  • 更新时间 :
  • 英文 :


我正在尝试创建一个函数,根据用户输入创建组并分配每个组的数量。

例如:

// Input
User input: 150
// Rule
Maximum quantity per group: 100
// Created groups
Group 1: { quantity: 100 }
Group 2: { quantity: 50 }

这是我想要的结果:

[{ quantity: 100 }, { quantity: 50 }]

What I have try

function group(input, maximum) {
let arr = (new Array(Math.floor(input / maximum))).fill(maximum);
input % maximum && arr.push(input % maximum);
console.log(arr);
}
group(150, 100);

这将返回给我:[100, 50]

现在我试着实现这个来输出一个对象:

function group(input, maximum) {
let arr = (new Array({quantity: Math.floor(input / maximum)})).fill(maximum);
input % maximum && arr.push({quantity: input % maximum});
console.log(arr);
}
group(150, 100);

返回me:[100, { "quantity": 50 }].

quantity只添加到第二个元素,而不添加到第一个元素。

我怎么能解决这个问题,所以所有的数组元素是一个对象?

正如评论中所指出的,这个问题非常接近期望的目标。

这里有一种可能的方法来实现期望的目标结构。

function group(input, maximum) {
let arr = (new Array(Math.floor(input / maximum))).fill(maximum);
input % maximum && arr.push(input % maximum);

// instead of using "arr", simply transform it
// by putting the number as an object with prop-name "quantity"
console.log(arr.map(quantity => ({ quantity })));
}
group(150, 100);

在上面的代码片段中作为内联注释添加了解释。

最新更新