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

252
Views
Divide a number into equal values and push to an array

I need to divide a number equally and push the values on the array. I'm using 100 as an example, but when I do it, it goes [28, 24, 24, 24], and I need it to be [25, 25, 25, 25]

const divide = () => {
  var number = 100
  var n = 4

  var values = []
  while(number > 0 && n > 0){
    var a = Math.floor(number / n / 4) * 4
    number -= a
    n--
    values.push(a)
  }

  console.log(values)
}

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

0

If I understand your question correctly:

const divide = (num = 100, n = 4) => new Array(n).fill(num / n);
about 4 years ago · Juan Pablo Isaza Report

0

The Math.floor() function returns the largest integer less than or equal to a given number, in your code this functions make the result incorrect

this is a correct code :

const divide = () => {
  var number = 100
  var n = 4

  var values = []
  for(int i=1;i<=4;i++){
    values.push(a/4)
  }

  console.log(values)
}
about 4 years ago · Juan Pablo Isaza Report

0

Here is another version of doing it:

const divide = (num = 100, n = 4) => {
  const f=Math.floor(num/n);
  return [...Array(n)].map((_,i)=>i-n+1?f:num-i*f);
}
    
console.log(divide());
console.log(divide(100,3));

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!