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})())]
5
  • possible duplicate of Create a JavaScript array containing 1...N Commented Oct 15, 2014 at 14:29
  • @antyrat slightly different, this one's m..n. Not all answers there are applicable. Commented Oct 15, 2014 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. Commented Oct 15, 2014 at 14:35
  • @DavidSherret I'm indeed after readability, I could just use underscore's range otherwise. Commented Oct 15, 2014 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? Commented Oct 23, 2016 at 0:03

2 Answers 2

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]
Sign up to request clarification or add additional context in comments.

2 Comments

Trying any of those lines in Chrome's console produces nothing but: eferenceError: Invalid left-hand side in assignment
@DavidThomas This is a EcmaScript 6 code. In chrome I think you need to enable it to make it work (maybe via chrome://flags ?).
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;
}

1 Comment

you never said anything about it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.