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

290
Views
Javascript: return all rangs between two numbers based on a number

I have a case where I need to split a range of numbers [1, 60] into ranges that has 11 in each.

I want to push each range into JSON Array, so the expected result would be:

[
{'first: 1, 'last': 11},  // count = 11
{'first: 12, 'last': 22}, // count = 11
{'first: 23, 'last': 33}, // count = 11
{'first: 34, 'last': 44}, // count = 11
{'first: 45, 'last': 55}, // count = 11
{'first: 56, 'last': 60}  // the rest, count = 5
]

My code so far:

var count = 11, first = 1, last = 60;
var all = [];
var starter = first;
for(i = first; i <= last; i++){
if(i % count == 0){
all.push({'first': (i - count + (all.length == 0 ? 1 : 0)), 'last': (i-1)});
 }
}
console.log(all);

My code return only 5 ranges not 6 as expected and this code not work for all cases like [1, 10] and it return wrong result in many other cases.

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

0

var count = 11, first = 1, last = 60;
var all = [];
for(i = first; i <= last; i += count){
    var l = i + count - 1;
    all.push({'first': i, 'last': l > last ? last : l});
}
console.log(all);
about 4 years ago · Juan Pablo Isaza Report

0

You could take a multiple of count and get the ranges.

function getRanges(first, to, count) {
    const result = [];
    while (first < to) {
        let last = Math.min(to, (Math.floor(first / count) + 1) * count);
        if (last + 1 === to) last = to;
        result.push({ first, last });
        first = last + 1;
    }
    return result;
}

console.log(getRanges(1, 60, 11));
console.log(getRanges(1, 11, 5));
.as-console-wrapper { max-height: 100% !important; top: 0; }

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!