Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to do a "flat push" in javascript?

I want to push all individual elements of a source array onto a target array,

target.push(source); 

puts just source's reference on the target list.

In stead I want to do:

for (i = 0; i < source.length; i++) {     target.push(source[i]); } 

Is there a way in javascript to do this more elegant, without explicitly coding a repetition loop?

And while I'm at it, what is the correct term? I don't think that "flat push" is correct. Googling did not yield any results as source and target are both arrays.

like image 557
dr jerry Avatar asked Oct 24 '10 09:10

dr jerry


People also ask

How do you write a push method in JavaScript?

JavaScript Array push()The push() method adds new items to the end of an array. The push() method changes the length of the array. The push() method returns the new length.

What is flat method in JavaScript?

flat() The flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.

How do you push a number in JavaScript?

The arr. push() method is used to push one or more values into the array. This method changes the length of the array by the number of elements added to the array. Parameters This method contains as many numbers of parameters as the number of elements to be inserted into the array.


2 Answers

You could use the concat method:

var num1 = [1, 2, 3];   var num2 = [4, 5, 6];   var num3 = [7, 8, 9];    // creates array [1, 2, 3, 4, 5, 6, 7, 8, 9]; num1, num2, num3 are unchanged   var nums = num1.concat(num2, num3); 
like image 37
Darin Dimitrov Avatar answered Oct 06 '22 02:10

Darin Dimitrov


apply does what you want:

var target = [1,2]; var source = [3,4,5];  target.push.apply(target, source);  alert(target); // 1, 2, 3, 4, 5 

MDC - apply

Calls a function with a given this value and arguments provided as an array.

like image 71
25 revs, 4 users 83% Avatar answered Oct 06 '22 02:10

25 revs, 4 users 83%