-2

I have a string representation of a numerical range

var range = '6-14';

I want to create an array of integers represented by this range

[6,7,8,9,10,11,12,13,14]

I could implement this simple enough as a for loop but that seems like a clunky, brute force method. Can this be done in a short or more elegant way?

Jeff
  • 13,943
  • 11
  • 55
  • 103
  • To avoid closure due to opinions, please change the question from "short or more elegant" to something measurable, such as "fewer CPU cycles", or "fewer lines of code", or whatever you're looking for. – Jonathan M May 01 '17 at 14:54
  • 4
    http://stackoverflow.com/questions/3895478/does-javascript-have-a-method-like-range-to-generate-an-array-based-on-suppl – Daniel A. White May 01 '17 at 14:55
  • Try looking up array comprehension – Archmede May 01 '17 at 14:55
  • Thanks Jonathan. I thought "elegant" might be dodgy but in my defense, I also said "short". Tried searching and didnt find the duplicate. Thanks for the direction. – Jeff May 01 '17 at 14:58

1 Answers1

2

const [start, end] = '6-14'.split('-').map(n => Number(n));
const result = Array.from(Array(10), (_, i) => i+start)
console.info(result);

Array creation extracted from my answer here. You can find other alternative ways in the same question: Create a JavaScript array containing 1...N

Community
  • 1
  • 1
zurfyx
  • 31,043
  • 20
  • 111
  • 145