How to create a range of numbers from 1 to 5 in an array

Viewed 1559

I want to get as a result [1, 2, 3, 4, 5] in array. What am doing wrong? Do I have to decrease endNum?

function rangeOfNumbers(startNum, endNum) {
  if (endNum - startNum >= 0){
    const array = rangeOfNumbers(startNum, endNum);
    array.push(startNum);
    return rangeOfNumbers(startNum + 1, endNum);
  } else {
    return [];
  }
};
console.log(rangeOfNumbers(1, 5));

5 Answers
console.log([...Array(6).keys()].slice(1))

OUTPUT: [1, 2, 3, 4, 5]

"Under the hood" an array in JavaScript is actually an object with keys that are integers. The code spreads the keys of an array of length 6 to another array.

The slice method returns the second through the last element.

If you are looking for a range function, try this:

var range = (start, stop, step=1) => {
    const length = Math.ceil((stop - start) / step);
    return Array.from({length}, (_, i) => (i * step) + start);
}

range(1, 6)

OUTPUT: [1, 2, 3, 4, 5]

Short and concise:

Read about this method in this great anwer

const rangeOfNumbers = (a,b) => [...Array(b+1).keys()].slice(a)

console.log( rangeOfNumbers(1,5) )
console.log( rangeOfNumbers(5,10) )

The above isn't ideal when the parameters are quite large numbers, the code will needlessly generate a large array only for a small slice:

rangeOfNumbers(1000000,1000005)

Let's try to make a function which is more "considerate" on resources:

const rangeOfNumbers = (a,b) => [...Array(b-a)].map((_,i) => i+a+1)

console.log( rangeOfNumbers(1000000, 1000005) )

Getting range numbers using recursion in JavaScript

function rangeOfNumbers(startNum, endNum) {
 if (startNum - endNum === 0) {
  return [startNum];
 } else {
  const numbers = rangeOfNumbers(startNum + 1, endNum);    
  numbers.unshift(startNum);
  return numbers;
 }
};

try this :

 const array=Array();
    function rangeOfNumbers(startNum, endNum) {
      if(endNum-startNum>=0){
        console.log(startNum)
        array.push(startNum);
       return rangeOfNumbers(startNum+1,endNum);
        
      }else{
        return array;
      }
    };
    console.log(rangeOfNumbers(1,5));

This should do the job with for loop.

function rangeOfNumbers(a, b){
 let arr = [];
 for(a; a<=b; a++){
  arr.push(a)
 }
 return arr;
}
Related