Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy array items into another array

I have a JavaScript array dataArray which I want to push into a new array newArray. Except I don't want newArray[0] to be dataArray. I want to push in all the items into the new array:

var newArray = [];  newArray.pushValues(dataArray1); newArray.pushValues(dataArray2); // ... 

or even better:

var newArray = new Array (    dataArray1.values(),    dataArray2.values(),    // ... where values() (or something equivalent) would push the individual values into the array, rather than the array itself ); 

So now the new array contains all the values of the individual data arrays. Is there some shorthand like pushValues available so I don't have to iterate over each individual dataArray, adding the items one by one?

like image 572
bba Avatar asked Nov 11 '10 15:11

bba


People also ask

How do I move an element from one array to another?

Create a temp variable and assign the value of the original position to it. Now, assign the value in the new position to original position. Finally, assign the value in the temp to the new position.


1 Answers

Use the concat function, like so:

var arrayA = [1, 2]; var arrayB = [3, 4]; var newArray = arrayA.concat(arrayB); 

The value of newArray will be [1, 2, 3, 4] (arrayA and arrayB remain unchanged; concat creates and returns a new array for the result).

like image 184
WiseGuyEh Avatar answered Oct 17 '22 17:10

WiseGuyEh