Is there a built in way to create an Array of numbers between two numbers in Javascript?

Viewed 68

I'm given a number. I need to create an array that contains 4 numbers below it, the number itself and then 4 numbers above it.

My naive approach was to create 2 for loops, but I feel like there's a more efficient way to do this using some ES6 syntax.

For example:

generateArray(240) // [236, 237, 238, 239, 240, 241, 242, 243, 244 ];

2 Answers
const generateArray = 
    (aroundNumber) => [...Array(9).keys()].map(i => i + aroundNumber - 4);

generateArray(240) // [236, 237, 238, 239, 240, 241, 242, 243, 244 ];

Explanation:

  1. Array(9) is creating an array of 9 elements
  2. keys() methods would return 1,2,3,4,5,6,7,8,9
  3. map transforms it to the range you need - it takes the i (the number you are transforming to something else) and adds an offset to it (in this case aroundNumber - 4 because your array is starting 4 elements below the number)

Also, as @Estradiaz mentioned in the comments, you can use Array.from method

  const generateArray = 
    (aroundNumber) => Array.from({length: 9}, (v, i) => i + aroundNumber - 4);

You can read more about the Array.from() method here

Here's how i would do it

const generateArray = 
    (aroundNumber, range) => Array(range * 2 + 1).fill(0).map((_, index) => index + aroundNumber - range);

console.log(generateArray(240, 4));


// alternatively generator

function* generateArrayGenerator (value, range) {
  value = value - range;

  for(let _ of Array(range * 2 + 1)) {
    yield value++;
  }
}

console.log([...generateArrayGenerator(240, 4)])

Related