0

My code is working, but it looks very creepy.

ar2.push(pr1);ar2.push(pr2);ar2.push(pr3);ar2.push(pr4);ar2.push(pr5);ar2.push(pr6);

basically all those pr1, pr2 things are declared const... I was trying to add them to the array using a for loop, to no avail. Is there any way to do a one liner for this?

OlegArsyonov
  • 1,251
  • 1
  • 14
  • 18
  • Possible duplicate of [push multiple elements to array](https://stackoverflow.com/questions/14723848/push-multiple-elements-to-array) – adiga Mar 31 '19 at 05:45
  • If the variables `pr1, pr2, ...` are declared with `var` instead of `const`, you will be able to use a loop. However, you will have to trade off the properties that `const` gives to the variables. – Shidersz Mar 31 '19 at 06:17

2 Answers2

0

push accepts multiple parameters, so you can just list them all when you push:

ar2.push(pr1, pr2, pr3, pr4, pr5, pr6);

That said, it's a bit of a code smell to have so many standalone variable names - if possible, you might consider modifying your code such that the prs are defined in an array to begin with, rather than pushing afterwards.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • But it's still too long though. Is there any way to iterate/loop through the names? I was trying to use both ++ and ${``} to no avail.. – OlegArsyonov Mar 31 '19 at 05:45
  • 1
    Ideally, change your code so that the `pr`s are all in an array *initially*, rather than `push`ing after the fact, though without seeing the context of how the `pr`s are defined, it's hard to say (feel free to edit that into your quesiton) – CertainPerformance Mar 31 '19 at 05:46
  • Opinion-based, but I completely disagree. Mutation should be avoided when not necessary - code is easier to reason about when objects don't change after they're declared. – CertainPerformance Mar 31 '19 at 05:54
0

Just use Array.prototype.push.apply:

Array.prototype.push.apply(ar2, [pr1, pr2, pr3, pr4, pr5, pr6]);
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79