/    Sign up×
Community /Pin to ProfileBookmark

How to push values from one array to another

Let’s say i have two arrays:

var array1 = [“1″,”2″,”3”];

var finalArray = [];

and I want to dump the values of array1 into finalArray several times to end up with the value of finalArray being:

“1”,”2″,”3″,”1″,”2″,”3″,”1″,”2″,”3″

What would be the easiest way to dump the values into the other without making it multidimensional?

thanks

to post a comment
JavaScript

7 Comments(s)

Copy linkTweet thisAlerts:
@JMRKERMar 29.2011 — Possibly consider using the concat() function.

See: http://www.w3schools.com/jsref/jsref_concat_array.asp
<i>
</i>var finalArray = [].concat(array1,array1,array1);
Copy linkTweet thisAlerts:
@JericoauthorMar 30.2011 — thanks. That saves a bit of code. However, I had to do it like this:

[CODE]function(num){
for(var i=0;i<num;i++){
this.myArray2 = this.myArray2.concat(this.myArray1);

}[/CODE]
Copy linkTweet thisAlerts:
@mrhooMar 30.2011 — You shouldn't need the loop-

JMRKER's code works in all the browsers I have handy:

[CODE]var A=[1,2,3,4,5];
A=A.concat(A,A,A);
alert(A)[/CODE]


returned value: (Array)

[1,2,3,4,5,1,2,3,4,5,1,2,3,4,5,1,2,3,4,5]
Copy linkTweet thisAlerts:
@JericoauthorMar 30.2011 — I need the loop because 'num' can be any number passed to the function.
Copy linkTweet thisAlerts:
@JMRKERMar 30.2011 — thanks. That saves a bit of code. However, I had to do it like this:

[CODE]function(num){
for(var i=0;i<num;i++){
this.myArray2 = this.myArray2.concat(this.myArray1);

}[/CODE]
[/QUOTE]


Why did you have to change it? Are you trying to use it in a prototype assignment?

?
Copy linkTweet thisAlerts:
@JericoauthorMar 30.2011 — I don't know what a prototype assignment is.

My point is that the number of times the arrays need to be concatenated is dynamic. If I knew ahead of time how many times, then your way would be fine - hence the loop.
Copy linkTweet thisAlerts:
@JMRKERMar 30.2011 — Dynamic assignment is OK. No problem with function use then.

I was questioning the use of 'this' in the function.

It is typically used when defining a prototype function.

I'm not sure it is needed in your function, but if it works to your needs, keep goin' ?
×

Success!

Help @Jerico spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.28,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...