In PHP, you can use the range function to generate a sequence of numbers or characters between a specified start and end value. For example:
range(1, 3); // Array(1, 2, 3)
range(“A”, “C”); // Array(“A”, “B”, “C”)
Is there an equivalent built-in function in JavaScript to achieve the same functionality? If not, how could this be implemented in JavaScript?
In JavaScript, there isn’t a built-in function that directly mimics PHP’s range function. However, you can achieve similar functionality way by using Array.from() and a mapping function:
You can use Array.from() to create an array from a given length and map each element to the desired value.
function range(start, end) {
return Array.from({ length: end - start + 1 }, (_, i) => start + i);
}
console.log(range(1, 3)); // [1, 2, 3]
console.log(range("A".charCodeAt(0), "C".charCodeAt(0)).map(code => String.fromCharCode(code))); // ["A", "B", "C"]
Try using a for loop can also help, simple for loop to generate the array elements between the start and end values.
function range(start, end) {
let result = [];
for (let i = start; i <= end; i++) {
result.push(i);
}
return result;
}
console.log(range(1, 3)); // [1, 2, 3]
console.log(range("A".charCodeAt(0), "C".charCodeAt(0)).map(code => String.fromCharCode(code))); // ["A", "B", "C"]
You can implement a recursive function to generate the range of values.
function range(start, end, result = []) {
return start > end ? result : range(start + 1, end, result.concat(start));
}
console.log(range(1, 3)); // [1, 2, 3]
console.log(range("A".charCodeAt(0), "C".charCodeAt(0)).map(code => String.fromCharCode(code))); // ["A", "B", "C"]