Javascript: Using Array.map() without using currentValue (no-unused-vars)

Created on 14 Dec 2018  路  5Comments  路  Source: airbnb/javascript

I'm in a situation where I'm trying to make an array of random x y coordinates but the underscore in the map function is being flagged as an unused var. I'm not sure if there is a better way to write this or if I should simply do an inline ignore in this case.

In short: how do I avoid the no-unused-vars error when I don't need the currentValue required by the Array.map() method?

const getRandomInt = max => Math.floor(Math.random() * Math.floor(max));
const myCoolArray = new Array(25)
  .fill({})
  .map(_ => ({
    x: getRandomInt(100),
    y: getRandomInt(100)
  }))
question

All 5 comments

I鈥檇 suggest never using new Array ever, for any reason, full stop.

What you want here is:

const myCoolArray = Array.from({ length: 25 }, () => ({
  x: getRandomInt(100),
  y: getRandomInt(100),
});

To your original question, instead of _, use ().

TIL Array.from({length: X}) . . I don't believe that trick is widely known.

https://github.com/airbnb/javascript#arrays--from-array-like :-)

Thanks @ljharb !! That's a very neat solution.

Was this page helpful?
0 / 5 - 0 ratings