Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Using Array.map() without using currentValue (no-unused-vars) #1970

Closed
borrascador opened this issue Dec 14, 2018 · 5 comments
Closed

Using Array.map() without using currentValue (no-unused-vars) #1970

borrascador opened this issue Dec 14, 2018 · 5 comments
Labels

Comments

@borrascador
Copy link

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)
  }))
@ljharb
Copy link
Collaborator

ljharb commented Dec 14, 2018

I’d 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),
});

@ljharb ljharb closed this as completed Dec 14, 2018
@ljharb
Copy link
Collaborator

ljharb commented Dec 14, 2018

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

@ericblade
Copy link

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

@ljharb
Copy link
Collaborator

ljharb commented Dec 15, 2018

@borrascador
Copy link
Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants