Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

Does JavaScript have a method like “range()” to generate a range within the supplied bounds?

In PHP, you can do...
range(1, 3); // Array(1, 2, 3)
range("A", "C"); // Array("A", "B", "C")


That is, there is a function that allows you to get a scope of numbers or characters bypassing the upper and lower limits.

Is there anything built-in to JavaScript natively for this? If not, how would I implement it?
by

2 Answers

akshay1995
My new favorite form (ES2015)

Array(10).fill(1).map((x, y) => x + y)

And if you need a function with a step param:

const range = (start, stop, step = 1) =>
Array(Math.ceil((stop - start) / step)).fill(start).map((x, y) => x + y * step)
kshitijrana14
It works for characters and numbers, going forwards or backwards with an optional step.
var range = function(start, end, step) {
var range = [];
var typeofStart = typeof start;
var typeofEnd = typeof end;

if (step === 0) {
throw TypeError("Step cannot be zero.");
}

if (typeofStart == "undefined" || typeofEnd == "undefined") {
throw TypeError("Must pass start and end arguments.");
} else if (typeofStart != typeofEnd) {
throw TypeError("Start and end arguments must be of same type.");
}

typeof step == "undefined" && (step = 1);

if (end < start) {
step = -step;
}

if (typeofStart == "number") {

while (step > 0 ? end >= start : end <= start) {
range.push(start);
start += step;
}

} else if (typeofStart == "string") {

if (start.length != 1 || end.length != 1) {
throw TypeError("Only strings with one character are supported.");
}

start = start.charCodeAt(0);
end = end.charCodeAt(0);

while (step > 0 ? end >= start : end <= start) {
range.push(String.fromCharCode(start));
start += step;
}

} else {
throw TypeError("Only string and number types are supported");
}

return range;

}

Login / Signup to Answer the Question.