Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

116
Views
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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!