Skip to content

Instantly share code, notes, and snippets.

@davesag
Last active August 29, 2015 14:10
Show Gist options
  • Save davesag/cf861315ac6ea2aecba0 to your computer and use it in GitHub Desktop.
Save davesag/cf861315ac6ea2aecba0 to your computer and use it in GitHub Desktop.
Turning ranges into arrays.

Say you have a range of integers - 0 thru 100, and you wish to create an Array containing elements [0, 1, 2, … 100], what's the simplest way to do it?

For me the easiest has to be:

var results = []
for (var i = 0, l = 101; i < l; i++) { results.push(i) }

Another approach is to do this:

Array.apply(null, {length: 101}).map(Number.call, Number)

Personally I favour the first approach as it's very clear; but the second approach certainly is interesting.

A more comprehensive variant on the first approach is as follows:

function range(start, stop, step){
  if (typeof stop == 'undefined') { stop = start; start = 0 }
  if (typeof step == 'undefined'){ step = 1 }
  if ((step > 0 && start >= stop) || (step < 0 && start <= stop)) return []
  var result = []
  for (var i = start; step > 0 ? i < stop : i > stop; i += step) { result.push(i) }
  return result
}

This allows you to do stuff like var arry = range(101) or var arry = range(5,51,15) => [5, 20, 35, 50] but for a one-off use it's a bit overkill.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment