'How to create groups and allocate a quantity per group depending on maximum value per group?
I am trying to create a function that creates groups and allocates a quantity per group, depending on the user input.
For example:
// Input
User input: 150
// Rule
Maximum quantity per group: 100
// Created groups
Group 1: { quantity: 100 }
Group 2: { quantity: 50 }
Goal
This is my desired outcome:
[{ quantity: 100 }, { quantity: 50 }]
What I have tried
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);
Output
This will return me: [100, 50].
Now I tried implementing this to output me an object:
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);
Output
This returns me: [100, { "quantity": 50 }].
quantity is only added to the second element, but not the first.
Question
How can I fix this, so all the array elements is an object?
Solution 1:[1]
As noted in the comment, the question is very close to the desired objective.
Here's one possible way to achieve the desired target structure.
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);
Explanation added as inline comments in the above snippet.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | jsN00b |
