Skip to content

Instantly share code, notes, and snippets.

@StevenACoffman
Last active December 23, 2015 23:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save StevenACoffman/dea44b7af45a363a345b to your computer and use it in GitHub Desktop.
Save StevenACoffman/dea44b7af45a363a345b to your computer and use it in GitHub Desktop.
Generate an array in a particular range
const start = 5;
const end = 20;
let myArray = Array.from(new Array(end - start)).map((_, index) => start + index);
console.log(myArray); // -> 5,6,7,8,9,10,11,12,13,14,15,16,17,18,19
//alernative
myArray = [...(new Array(end - start))].map((_, index) => start + index);
console.log(myArray); // -> 5,6,7,8,9,10,11,12,13,14,15,16,17,18,19
//alternative: arrayFrom takes optional map function parameter to avoid intermediate creation
myArray = Array.from(new Array(end - start),((_, index) => start + index)); // -> 5,6,7,8,9,10,11,12,13,14,15,16,17,18,19
function range(start=0, stop=0, step = 1) {
if (!stop) {
stop = start || 0;
start = 0;
}
var length = Math.max(Math.ceil((stop - start) / step), 0)
return Array.from({length}, (x, i) => (i * step) + start);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment