2

Is there a nice one liner for a range array in javascript, equivalent to python's list(range(m, n))? ES6 permitted. Here's the best I've come up with so far:

[x for(x of (function*(){for(let i=0;i<100;i++) yield i})())]
simonzack
  • 19,729
  • 13
  • 73
  • 118
  • possible duplicate of [Create a JavaScript array containing 1...N](http://stackoverflow.com/questions/3746725/create-a-javascript-array-containing-1-n) – antyrat Oct 15 '14 at 14:29
  • @antyrat slightly different, this one's `m..n`. Not all answers there are applicable. – simonzack Oct 15 '14 at 14:30
  • 1
    Just create a function like `CreateRange(5, 10)`. Any trick one line solution I can think of is not very readable in JS. – David Sherret Oct 15 '14 at 14:35
  • @DavidSherret I'm indeed after readability, I could just use underscore's range otherwise. – simonzack Oct 15 '14 at 14:42
  • I agree with @DavidSherret, there's no good one line. The closest would be `Array.from({length:10-5}, (v,k) => k + 5)` but I don't find it to be terribly succint. Why does it have to be one line btw? – CervEd Oct 23 '16 at 00:03

2 Answers2

9

You can use Array.from and arrow functions for a better readability:

Array.from({length: 4}, (_, n) => n) // = [0, 1, 2, 3]
Array.from({length: 5}, (_, n) => n+6) // = [6, 7, 8, 9, 10]
Array.from({length: 6}, (_, n) => n-3) // = [-3, -2, -1, 0, 1, 2]
Sebastien C.
  • 4,649
  • 1
  • 21
  • 32
  • Trying any of those lines in Chrome's console produces nothing but: `eferenceError: Invalid left-hand side in assignment` – David Thomas Oct 15 '14 at 14:59
  • 1
    @DavidThomas This is a EcmaScript 6 code. In chrome I think you need to enable it to make it work (maybe via chrome://flags ?). – Sebastien C. Oct 15 '14 at 15:25
0

You can just do this

var arr = [];  while(arr[arr.length-1] !== end) arr.push(start++); // one-liner

Making the above to a function will result in

function createRange(start, end) {
   var arr = [];  while(arr[arr.length-1] !== end) arr.push(start++); // one-liner
   return arr;
}
Amit Joki
  • 58,320
  • 7
  • 77
  • 95