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?

2
  • Possible duplicate of push multiple elements to array Commented Mar 31, 2019 at 5: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. Commented Mar 31, 2019 at 6:17

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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..
Ideally, change your code so that the prs are all in an array initially, rather than pushing after the fact, though without seeing the context of how the prs are defined, it's hard to say (feel free to edit that into your quesiton)
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.
0

Just use Array.prototype.push.apply:

Array.prototype.push.apply(ar2, [pr1, pr2, pr3, pr4, pr5, pr6]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.