Copy array items into another array
Olivia Zamora
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?
18 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).
In ECMAScript 6, you can use the Spread syntax:
let arr1 = [0, 1, 2];
let arr2 = [3, 4, 5];
arr1.push(...arr2);
console.log(arr1)Spread syntax is available in all major browsers (that excludes IE11). For the current compatibility, see this (continuously updated) compatibility table.
However, see Jack Giffin's reply below for more comments on performance. It seems concat is still better and faster than the spread operator.
Provided your arrays are not huge (see caveat below), you can use the push() method of the array to which you wish to append values. push() can take multiple parameters so you can use its apply() method to pass the array of values to be pushed as a list of function parameters. This has the advantage over using concat() of adding elements to the array in place rather than creating a new array.
However, it seems that for large arrays (of the order of 100,000 members or more), this trick can fail. For such arrays, using a loop is a better approach. See for details.
var newArray = [];
newArray.push.apply(newArray, dataArray1);
newArray.push.apply(newArray, dataArray2);You might want to generalize this into a function:
function pushArray(arr, arr2) { arr.push.apply(arr, arr2);
}... or add it to Array's prototype:
Array.prototype.pushArray = function(arr) { this.push.apply(this, arr);
};
var newArray = [];
newArray.pushArray(dataArray1);
newArray.pushArray(dataArray2);... or emulate the original push() method by allowing multiple parameters using the fact that concat(), like push(), allows multiple parameters:
Array.prototype.pushArray = function() { this.push.apply(this, this.concat.apply([], arguments));
};
var newArray = [];
newArray.pushArray(dataArray1, dataArray2);Here's a loop-based version of the last example, suitable for large arrays and all major browsers, including IE <= 8:
Array.prototype.pushArray = function() { var toPush = this.concat.apply([], arguments); for (var i = 0, len = toPush.length; i < len; ++i) { this.push(toPush[i]); }
}; 9 Found an elegant way from MDN
var vegetables = ['parsnip', 'potato'];
var moreVegs = ['celery', 'beetroot'];
// Merge the second array into the first one
// Equivalent to vegetables.push('celery', 'beetroot');
Array.prototype.push.apply(vegetables, moreVegs);
console.log(vegetables); // ['parsnip', 'potato', 'celery', 'beetroot']Or you can use the spread operator feature of ES6:
let fruits = [ 'apple', 'banana'];
const moreFruits = [ 'orange', 'plum' ];
fruits.push(...moreFruits); // ["apple", "banana", "orange", "plum"] 1 The following seems simplest to me:
var newArray = dataArray1.slice();
newArray.push.apply(newArray, dataArray2);As "push" takes a variable number of arguments, you can use the apply method of the push function to push all of the elements of another array. It constructs
a call to push using its first argument ("newArray" here) as "this" and the
elements of the array as the remaining arguments.
The slice in the first statement gets a copy of the first array, so you don't modify it.
Update If you are using a version of javascript with slice available, you can simplify the push expression to:
newArray.push(...dataArray2) 1 ๐ฅ๐ฒ๐๐ฒ๐ฎ๐ฟ๐ฐ๐ต ๐๐ป๐ฑ ๐๐ฒ๐ป๐ฐ๐ต๐บ๐ฎ๐ฟ๐ธ๐ ๐ฃ๐ผ๐๐ฒ๐ฟ๐ณ๐๐น๐น๐ ๐ฆ๐ต๐ผ๐ ๐ง๐ต๐ฎ๐ ๐๐ผ๐ป๐ฐ๐ฎ๐ ๐๐ ๐ง๐ต๐ฒ ๐๐ฒ๐๐ (for the original question)
For the facts, a performance test at jsperf and checking some things in the console are performed. For the research, the website irt.org is used. Below is a collection of all these sources put together plus an example function at the bottom.
โโโโโโโโโโโโโโโโโฆโโโโโโโฆโโโโโโโโโโโโโโโโโโฆโโโโโโโโโโโโโโโโฆโโโโโโโโโโฆโโโโโโโโโโโ โ Method โConcatโslice&push.apply โ push.apply x2 โ ForLoop โSpread โ โ โโโโโโโโโโโโโโโโฌโโโโโโโฌโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโฌโโโโโโโโโโฌโโโโโโโโโโโฃ โ mOps/Sec โ179 โ104 โ 76 โ 81 โ28 โ โ โโโโโโโโโโโโโโโโฌโโโโโโโฌโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโฌโโโโโโโโโโฌโโโโโโโโโโโฃ โ Sparse arrays โYES! โOnly the sliced โ no โ Maybe2 โno โ โ kept sparse โ โarray (1st arg) โ โ โ โ โ โโโโโโโโโโโโโโโโฌโโโโโโโฌโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโฌโโโโโโโโโโฌโโโโโโโโโโโฃ โ Support โMSIE 4โMSIE 5.5 โ MSIE 5.5 โ MSIE 4 โEdge 12 โ โ (source) โNNav 4โNNav 4.06 โ NNav 4.06 โ NNav 3 โMSIENNavโ โ โโโโโโโโโโโโโโโโฌโโโโโโโฌโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโฌโโโโโโโโโโฌโโโโโโโโโโโฃ โArray-like actsโno โOnly the pushed โ YES! โ YES! โIf have โ โlike an array โ โarray (2nd arg) โ โ โiterator1โ โโโโโโโโโโโโโโโโโฉโโโโโโโฉโโโโโโโโโโโโโโโโโโฉโโโโโโโโโโโโโโโโฉโโโโโโโโโโฉโโโโโโโโโโโ1 If the array-like object does not have a Symbol.iterator property, then trying to spread it will throw an exception.2 Depends on the code. The following example code "YES" preserves sparseness.
function mergeCopyTogether(inputOne, inputTwo){ var oneLen = inputOne.length, twoLen = inputTwo.length; var newArr = [], newLen = newArr.length = oneLen + twoLen; for (var i=0, tmp=inputOne[0]; i !== oneLen; ++i) { tmp = inputOne[i]; if (tmp !== undefined || inputOne.hasOwnProperty(i)) newArr[i] = tmp; } for (var two=0; i !== newLen; ++i, ++two) { tmp = inputTwo[two]; if (tmp !== undefined || inputTwo.hasOwnProperty(two)) newArr[i] = tmp; } return newArr;
}As seen above, I would argue that Concat is almost always the way to go for both performance and the ability to retain the sparseness of spare arrays. Then, for array-likes (such as DOMNodeLists like document.body.children), I would recommend using the for loop because it is both the 2nd most performant and the only other method that retains sparse arrays. Below, we will quickly go over what is meant by sparse arrays and array-likes to clear up confusion.
๐ง๐ต๐ฒ ๐๐๐๐๐ฟ๐ฒ
At first, some people may think that this is a fluke and that browser vendors will eventually get around to optimizing Array.prototype.push to be fast enough to beat Array.prototype.concat. WRONG! Array.prototype.concat will always be faster (in principle at least) because it is a simple copy-n-paste over the data. Below is a simplified persuado-visual diagram of what a 32-bit array implementation might look like (please note real implementations are a LOT more complicated)
Byte โ Data here โโโโโโฌโโโโโโโโโโโ 0x00 โ int nonNumericPropertiesLength = 0x00000000 0x01 โ ibid 0x02 โ ibid 0x03 โ ibid 0x00 โ int length = 0x00000001 0x01 โ ibid 0x02 โ ibid 0x03 โ ibid 0x00 โ int valueIndex = 0x00000000 0x01 โ ibid 0x02 โ ibid 0x03 โ ibid 0x00 โ int valueType = JS_PRIMITIVE_NUMBER 0x01 โ ibid 0x02 โ ibid 0x03 โ ibid 0x00 โ uintptr_t valuePointer = 0x38d9eb60 (or whereever it is in memory) 0x01 โ ibid 0x02 โ ibid 0x03 โ ibid
As seen above, all you need to do to copy something like that is almost as simple as copying it byte for byte. With Array.prototype.push.apply, it is a lot more than a simple copy-n-paste over the data. The ".apply" has to check each index in the array and convert it to a set of arguments before passing it to Array.prototype.push. Then, Array.prototype.push has to additionally allocate more memory each time, and (for some browser implementations) maybe even recalculate some position-lookup data for sparseness.
An alternative way to think of it is this. The source array one is a large stack of papers stapled together. The source array two is also another large stack of papers. Would it be faster for you to
- Go to the store, buy enough paper needed for a copy of each source array. Then put each source array stacks of paper through a copy-machine and staple the resulting two copies together.
- Go to the store, buy enough paper for a single copy of the first source array. Then, copy the source array to the new paper by hand, ensuring to fill in any blank sparse spots. Then, go back to the store, buy enough paper for the second source array. Then, go through the second source array and copy it while ensuring no blank gaps in the copy. Then, staple all the copied papers together.
In the above analogy, option #1 represents Array.prototype.concat while #2 represents Array.prototype.push.apply. Let us test this out with a similar JSperf differing only in that this one tests the methods over sparse arrays, not solid arrays. One can find it right here.
Therefore, I rest my case that the future of performance for this particular use case lies not in Array.prototype.push, but rather in Array.prototype.concat.
๐๐น๐ฎ๐ฟ๐ถ๐ณ๐ถ๐ฐ๐ฎ๐๐ถ๐ผ๐ป๐
๐ฆ๐ฝ๐ฎ๐ฟ๐ฒ ๐๐ฟ๐ฟ๐ฎ๐๐
When certain members of the array are simply missing. For example:
// This is just as an example. In actual code,
// do not mix different types like this.
var mySparseArray = [];
mySparseArray[0] = "foo";
mySparseArray[10] = undefined;
mySparseArray[11] = {};
mySparseArray[12] = 10;
mySparseArray[17] = "bar";
console.log("Length: ", mySparseArray.length);
console.log("0 in it: ", 0 in mySparseArray);
console.log("arr[0]: ", mySparseArray[0]);
console.log("10 in it: ", 10 in mySparseArray);
console.log("arr[10] ", mySparseArray[10]);
console.log("20 in it: ", 20 in mySparseArray);
console.log("arr[20]: ", mySparseArray[20]);Alternatively, javascript allows you to initialize spare arrays easily.
var mySparseArray = ["foo",,,,,,,,,,undefined,{},10,,,,,"bar"];๐๐ฟ๐ฟ๐ฎ๐-๐๐ถ๐ธ๐ฒ๐
An array-like is an object that has at least a length property, but was not initialized with new Array or []; For example, the below objects are classified as array-like.
{0: "foo", 1: "bar", length:2}document.body.children
new Uint8Array(3)
- This is array-like because although it's a(n) (typed) array, coercing it to an array changes the constructor.
(function(){return arguments})()Observe what happens using a method that does coerce array-likes into arrays like slice.
var slice = Array.prototype.slice;
// For arrays:
console.log(slice.call(["not an array-like, rather a real array"]));
// For array-likes:
console.log(slice.call({0: "foo", 1: "bar", length:2}));
console.log(slice.call(document.body.children));
console.log(slice.call(new Uint8Array(3)));
console.log(slice.call( function(){return arguments}() ));- NOTE: It is bad practice to call slice on function arguments because of performance.
Observe what happens using a method that does not coerce array-likes into arrays like concat.
var empty = [];
// For arrays:
console.log(empty.concat(["not an array-like, rather a real array"]));
// For array-likes:
console.log(empty.concat({0: "foo", 1: "bar", length:2}));
console.log(empty.concat(document.body.children));
console.log(empty.concat(new Uint8Array(3)));
console.log(empty.concat( function(){return arguments}() )); var a=new Array('a','b','c');
var b=new Array('d','e','f');
var d=new Array('x','y','z');
var c=a.concat(b,d)Does that solve your problem ?
0With JavaScript ES6, you can use the ... operator as a spread operator which will essentially convert the array into values. Then, you can do something like this:
const myArray = [1,2,3,4,5];
const moreData = [6,7,8,9,10];
const newArray = [ ...myArray, ...moreData,
];While the syntax is concise, I do not know how this works internally and what the performance implications are on large arrays.
2The function below doesn't have an issue with the length of arrays and performs better than all suggested solutions:
function pushArray(list, other) { var len = other.length; var start = list.length; list.length = start + len; for (var i = 0; i < len; i++ , start++) { list[start] = other[i]; }
}unfortunately, jspref refuses to accept my submissions, so here they are the results using benchmark.js
Name | ops/sec | ยฑ % | runs sampled
for loop and push | 177506 | 0.92 | 63
Push Apply | 234280 | 0.77 | 66
spread operator | 259725 | 0.40 | 67
set length and for loop | 284223 | 0.41 | 66where
for loop and push is:
for (var i = 0, l = source.length; i < l; i++) { target.push(source[i]); }Push Apply:
target.push.apply(target, source);spread operator:
target.push(...source);and finally the 'set length and for loop' is the above function
1Here's the ES6 way
var newArray = [];
let dataArray1 = [1,2,3,4]
let dataArray2 = [5,6,7,8]
newArray = [...dataArray1, ...dataArray2]
console.log(newArray)The above method is good to go for most of the cases and the cases it is not please consider
concat, like you have hundred thousands of items in arrays.
let dataArray1 = [1,2,3,4] let dataArray2 = [5,6,7,8] let newArray = dataArray1.concat(dataArray2); console.log(newArray) 0 If you want to modify the original array, you can spread and push:
var source = [1, 2, 3];
var range = [5, 6, 7];
var length = source.push(...range);
console.log(source); // [ 1, 2, 3, 5, 6, 7 ]
console.log(length); // 6If you want to make sure only items of the same type go in the source array (not mixing numbers and strings for example), then use TypeScript.
/** * Adds the items of the specified range array to the end of the source array. * Use this function to make sure only items of the same type go in the source array. */
function addRange<T>(source: T[], range: T[]) { source.push(...range);
} There are a number of answers talking about Array.prototype.push.apply. Here is a clear example:
var dataArray1 = [1, 2];
var dataArray2 = [3, 4, 5];
var newArray = [ ];
Array.prototype.push.apply(newArray, dataArray1); // newArray = [1, 2]
Array.prototype.push.apply(newArray, dataArray2); // newArray = [1, 2, 3, 4, 5]
console.log(JSON.stringify(newArray)); // Outputs: [1, 2, 3, 4, 5]If you have ES6 syntax:
var dataArray1 = [1, 2];
var dataArray2 = [3, 4, 5];
var newArray = [ ];
newArray.push(...dataArray1); // newArray = [1, 2]
newArray.push(...dataArray2); // newArray = [1, 2, 3, 4, 5]
console.log(JSON.stringify(newArray)); // Outputs: [1, 2, 3, 4, 5] Performance
I analyse current solutions and propose 2 new (F and G presented in details section) one which are extremely fast for small and medium arrays
Today 2020.11.13 I perform tests on MacOs HighSierra 10.13.6 on Chrome v86, Safari v13.1.2 and Firefox v82 for chosen solutions
Results
For all browsers
- solutions based on
while-pop-unshift(F,G) are (extremely) fastest on all browsers for small and medium size arrays. For arrays with 50000 elements this solutions slows down on Chrome - solutions C,D for arrays 500000 breaks: "RangeError: Maximum call stack size exceeded
- solution (E) is slowest
Details
I perform 2 tests cases:
- when arrays have 10 elements - you can run it HERE
- when arrays have 10k elements - you can run it HERE
Below snippet presents differences between solutionsA,B,C,D,E, F(my), G(my),H,I
//
function A(a,b) { return a.concat(b);
}
//
function B(a,b) { return [...a, ...b];
}
//
function C(a,b) { return (a.push(...b), a);
}
//
function D(a,b) { Array.prototype.push.apply(a, b); return a;
}
//
function E(a,b) { return b.reduce((pre, cur) => [...pre, cur], a);
}
// my
function F(a,b) { while(b.length) a.push(b.shift()); return a;
}
// my
function G(a,b) { while(a.length) b.unshift(a.pop()); return b;
}
//
function H(a, b) { var len = b.length; var start = a.length; a.length = start + len; for (var i = 0; i < len; i++ , start++) { a[start] = b[i]; } return a;
}
//
function I(a, b){ var oneLen = a.length, twoLen = b.length; var newArr = [], newLen = newArr.length = oneLen + twoLen; for (var i=0, tmp=a[0]; i !== oneLen; ++i) { tmp = a[i]; if (tmp !== undefined || a.hasOwnProperty(i)) newArr[i] = tmp; } for (var two=0; i !== newLen; ++i, ++two) { tmp = b[two]; if (tmp !== undefined || b.hasOwnProperty(two)) newArr[i] = tmp; } return newArr;
}
// ---------
// TEST
// ---------
let a1=[1,2,3];
let a2=[4,5,6];
[A,B,C,D,E,F,G,H,I].forEach(f=> { console.log(`${f.name}: ${f([...a1],[...a2])}`)
})And here are example results for chrome
We have two array a and b. the code what did here is array a value is pushed into array b.
let a = [2, 4, 6, 8, 9, 15]
function transform(a) { let b = ['4', '16', '64'] a.forEach(function(e) { b.push(e.toString()); }); return b;
}
transform(a)
[ '4', '16', '64', '2', '4', '6', '8', '9', '15' ] 1 Try this:
var arrayA = [1, 2];
var arrayB = [3, 4];
var newArray = arrayB.reduce((pre, cur) => [...pre, ...cur], arrayA);
console.log(newArray) instead of push() function use concat function for IE. example,
var a=a.concat(a,new Array('amin')); 1 ะขhis is a working code and it works fine:
var els = document.getElementsByTagName('input'), i;
var invnum = new Array();
var k = els.length;
for(i = 0; i < k; i++){invnum.push(new Array(els[i].id,els[i].value))} 0 public static void main(String[] args) { // TODO Auto-generated method stub //Scanner sc=new Scanner(System.in); int[] ij= {1,4,222,455,111}; int[] ijk=Arrays.copyOf(ij,ij.length); for(int i=0;i<ij.length;i++) { System.out.print(i); } System.out.println(" "); for(int i=0;i<ijk.length;i++) { System.out.print(i); }
}Output: 01234 01234
1