2

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 ];

javedb
  • 228
  • 2
  • 12
  • 1
    Does this answer your question? [Does JavaScript have a method like "range()" to generate a range within the supplied bounds?](https://stackoverflow.com/questions/3895478/does-javascript-have-a-method-like-range-to-generate-a-range-within-the-supp) – ehymel Jun 03 '20 at 15:13

2 Answers2

2
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

Kalman
  • 8,001
  • 1
  • 27
  • 45
1

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)])
Józef Podlecki
  • 10,453
  • 5
  • 24
  • 50