0

I'm trying to achieve the following:

const dayChooser = day => {
  const Monday = [];
  const Tuesday = [];
  const Wednesday = [];
  const Thursday = [];
  const Friday = [];
  const Saturday = [];
  const Sunday = [];

  day.push("It works!");
};

dayChooser(Monday);

console.log(Monday);

Should show:

[
  "It works!"
]

How can I achieve this? I tried googling for some solutions but I cannot seem to find an elegant solution to this. Surely there is an easy way to do this right?

EDIT: Found a solution finally:

const dayChooser = day => {
  const Monday = [];
  const Tuesday = [];
  const Wednesday = [];
  const Thursday = [];
  const Friday = [];
  const Saturday = [];
  const Sunday = [];

  day = eval(day)

  day.push("It works!");
  console.log(Monday)
}

dayChooser("Monday")
rago182
  • 185
  • 2
  • 15
  • I think that you should simply be passing the variable `Monday` instead of the string literal `"Monday"` to your `dayChooser` function call. – Richard Feb 04 '20 at 12:38
  • 1
    You can create an object with all your arrays in them and then pass the name of the array as an argument, or instead, just pass a reference to the array if it isn't dynamic – Nick Parsons Feb 04 '20 at 12:38
  • @NickParsons don't think this is a case for "variable variables". It's just confusion over how to pass a parameter which is an array. – VLAZ Feb 04 '20 at 12:39
  • I made a very stupid mistake in the example. I'm actually using React Native and cannto simply pass the variable Monday since the variable is declared in the function itself. Updating OP to reflect this now. – rago182 Feb 04 '20 at 12:40
  • @VLAZ hm, maybe, it would depend on whether OP gets the variable name dynamically somehow – Nick Parsons Feb 04 '20 at 12:40
  • 1
    @NickParsons OK, after the update *now* it's variable variables... – VLAZ Feb 04 '20 at 12:41
  • @rago182 `eval` is [discouraged](https://stackoverflow.com/questions/86513/why-is-using-the-javascript-eval-function-a-bad-idea). I suggest you see the second code snippet in the duplicate which involves making an object – Nick Parsons Feb 04 '20 at 12:49
  • 1
    @rago182 [this](https://jsfiddle.net/gtdn4k0f/) is how you may do it if you're using an object. – Nick Parsons Feb 04 '20 at 12:55

0 Answers0