3

I want to know if it is possible to make a method that takes two integer values as parameters and returns them and all the numbers between then in an array.

So for example if my method is

function getNumberRange(first, last)

And i call it

getNumberRanger(10, 13)

Is there a way for me to have the answer returned as the following array value

[10, 11, 12, 13]

Thanks in advance and sorry if this is badly worded.

Jonathan Wood
  • 65,341
  • 71
  • 269
  • 466
RobStallion
  • 1,624
  • 1
  • 15
  • 28

2 Answers2

6

Of course it is.

function getNumberRange(first, last) {
   var arr = [];
   for (var i = first; i <= last; i++) {
       arr.push(i);
   }
  return arr;
}

You may even want to add a check to make sure first is indeed last than greatest though to avoid errors. Maybe something like this:

if (first > last) {
    throw new Error("first must be less than last");
}
thatidiotguy
  • 8,701
  • 13
  • 60
  • 105
-1

Similar answer that handles sorting high and low

function makeArray(n1, n2) {
  var high = n1;
  var low = n2;
  if (n1 < n2) {
    high = n2;
    low = n1;
  }
  var myArray = [];
  for(var i=0; i < (high - low) + 1; i++) {
    myArray.push(low + i);
  }
  return myArray;
DvideBy0
  • 678
  • 2
  • 12
  • 27