Push 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?
javascript arrays
add a comment |
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?
javascript arrays
See this url stackoverflow.com/questions/351409/appending-to-array
– Jakir Hossain
Jan 10 '16 at 10:50
This should be the answer davidwalsh.name/combining-js-arrays
– starikovs
Sep 22 '17 at 8:24
add a comment |
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?
javascript arrays
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?
javascript arrays
javascript arrays
edited Sep 6 '18 at 22:36
Alexander Abakumov
4,53844169
4,53844169
asked Nov 11 '10 at 15:33
bbabba
4,78192525
4,78192525
See this url stackoverflow.com/questions/351409/appending-to-array
– Jakir Hossain
Jan 10 '16 at 10:50
This should be the answer davidwalsh.name/combining-js-arrays
– starikovs
Sep 22 '17 at 8:24
add a comment |
See this url stackoverflow.com/questions/351409/appending-to-array
– Jakir Hossain
Jan 10 '16 at 10:50
This should be the answer davidwalsh.name/combining-js-arrays
– starikovs
Sep 22 '17 at 8:24
See this url stackoverflow.com/questions/351409/appending-to-array
– Jakir Hossain
Jan 10 '16 at 10:50
See this url stackoverflow.com/questions/351409/appending-to-array
– Jakir Hossain
Jan 10 '16 at 10:50
This should be the answer davidwalsh.name/combining-js-arrays
– starikovs
Sep 22 '17 at 8:24
This should be the answer davidwalsh.name/combining-js-arrays
– starikovs
Sep 22 '17 at 8:24
add a comment |
15 Answers
15
active
oldest
votes
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).
5
A better reference would be: developer.mozilla.org/en/JavaScript/Reference/Global_Objects/… [1]: developer.mozilla.org/en/JavaScript/Reference/Global_Objects/…
– Jamund Ferguson
Feb 23 '11 at 5:41
71
Slow though: jsperf.com/concat-vs-push-apply/10
– w00t
Aug 20 '12 at 19:42
11
I agree that performant execution is very nice. BUT isn't concat exactly for that purpose to concat to arrays? So it should be standard. Or is there other better things to do with concat? And it might be slow only because of bad implementation of the JS engine of the browser or wherever you're using it in? It might be fixed one day. I would choose code maintainability over hacky speed optimizations. Hmm ....
– Bitterblue
Jun 10 '16 at 9:04
1
Also I just benchmarked the situation: concat vs. push.apply.Google Chrome
: fast (concat = winner),Opera
: fast (concat = winner),IE
: slower (concat = winner),Firefox
: slow (push.apply = winner, yet 10 times slower than Chrome's concat) ... speak of bad JS engine implementation.
– Bitterblue
Jun 10 '16 at 9:25
4
How is concatenating two arrays the accepted answer for how to push one into another?! Those are two different operations.
– kaqqao
Mar 6 '17 at 19:18
|
show 4 more comments
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 https://stackoverflow.com/a/17368101/96100 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]);
}
};
8
note:newArray.push.apply(newArray, dataArray1);
gives the same asArray.prototype.push.applay(newArray,dataArra1);
– user669677
Jul 5 '13 at 11:02
Is this compatible with older browsers?
– Damien Ó Ceallaigh
Apr 6 '18 at 0:53
developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
– Damien Ó Ceallaigh
Apr 6 '18 at 0:53
1
@DamienÓCeallaigh: Yes. This is all compatible with browsers going back to IE 6 and even earlier.
– Tim Down
Apr 9 '18 at 11:16
This is the epitome of poor programming practices.Array.prototype.concat
is not bad, rather it is simply misunderstood and sometimes misused. Under these circumstances, it is only misunderstood, but not misused.
– Jack Giffin
Aug 15 '18 at 10:23
|
show 3 more comments
I will add one more "future-proof" reply
In ECMAScript 6, you can use the spread operator:
var arr1 = [0, 1, 2];
var arr2 = [3, 4, 5];
arr1.push(...arr2);
Spread operator is not yet included in all major browsers. For the current compatibility, see this (continuously updated) compatibility table.
You can, however, use spread operator with Babel.js.
edit:
See Jack Giffin reply below for more comments on performance. It seems concat is still better and faster than spread operator.
3
You can also use the spread operator if you are using TypeScript. If you target ES5, it will compile tonewArray.apply(newArray, dataArray1)
.
– AJ Richardson
Feb 26 '16 at 21:28
4
Note: if you need the result in a third array (thus not modifying arr1, as the initial question seemed to require), you can do newArray = [...arr1, ...arr2]
– dim
Sep 29 '17 at 19:42
Oh I didn't know that. Thanks. I have added an edit comment.
– Karel Bílek
Aug 17 '18 at 5:47
Similar to how concat would function then, with the bonus of being persistent (mutating the original array).
– robertmylne
Sep 1 '18 at 8:37
@robertmylne The spread operator obviously does not modify the original array, instead creating a new copy of all the arrays contents desparsed.
– Jack Giffin
Nov 20 '18 at 2:44
add a comment |
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"]
This is not what the question was asking for. The question is asking for a way to create a new array each time, not modify an old array.
– Jack Giffin
Aug 15 '18 at 9:16
add a comment |
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 ?
add a comment |
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
Is also mentioned here at MDN as an example for "Merging two arrays"
– Wilt
Apr 27 '18 at 15:48
add a comment |
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]
add a comment |
The 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 | 66
where
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
This question is looking for a way to create a new array each time, not modify an existing array.
– Jack Giffin
Aug 15 '18 at 9:17
add a comment |
With 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.
2
If you take a look at how babel converts it, you'll see that it should not be any slower than usingArray.push.apply
technique.
– emil.c
Dec 11 '17 at 9:19
1
@JackGiffin I was just referring to what Ryan mentioned that he doesn't know how it works internally and what are performance implications, I wasn't actually suggesting this approach. In any case, you've done a very good job on your answer, nice research, it's always good to know such details.
– emil.c
Nov 22 '18 at 19:50
add a comment |
Here'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)
Hey budd there was a reason to develop and surely the reason wasn't speed . Speed matters when you have quite large array in that case concat is better
– Black Mamba
Nov 20 '18 at 3:37
add a comment |
Research And Results
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.
The Future
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.
Clarifications
Spare Arrays
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"];
Array-Likes
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 slice function argument 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}() ));
add a comment |
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
Please don't just post code as an answer. Explain what the code does and how it solves the problem.
– Patrick Hund
Jun 7 '17 at 18:28
add a comment |
instead of push() function use concat function for IE. example,
var a=a.concat(a,new Array('amin'));
both are very IE compatible
– Jack Giffin
Aug 16 '18 at 8:38
add a comment |
Т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))}
add a comment |
Most simple:
var newArray = dataArray1.slice(0);
1
This does not cover the problem in the question: concatenating two arrays.
– frasertweedale
May 8 '15 at 9:40
How does this try to answer the question?
– user6490459
Jan 30 at 15:05
add a comment |
protected by T J Jan 4 '16 at 17:12
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
15 Answers
15
active
oldest
votes
15 Answers
15
active
oldest
votes
active
oldest
votes
active
oldest
votes
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).
5
A better reference would be: developer.mozilla.org/en/JavaScript/Reference/Global_Objects/… [1]: developer.mozilla.org/en/JavaScript/Reference/Global_Objects/…
– Jamund Ferguson
Feb 23 '11 at 5:41
71
Slow though: jsperf.com/concat-vs-push-apply/10
– w00t
Aug 20 '12 at 19:42
11
I agree that performant execution is very nice. BUT isn't concat exactly for that purpose to concat to arrays? So it should be standard. Or is there other better things to do with concat? And it might be slow only because of bad implementation of the JS engine of the browser or wherever you're using it in? It might be fixed one day. I would choose code maintainability over hacky speed optimizations. Hmm ....
– Bitterblue
Jun 10 '16 at 9:04
1
Also I just benchmarked the situation: concat vs. push.apply.Google Chrome
: fast (concat = winner),Opera
: fast (concat = winner),IE
: slower (concat = winner),Firefox
: slow (push.apply = winner, yet 10 times slower than Chrome's concat) ... speak of bad JS engine implementation.
– Bitterblue
Jun 10 '16 at 9:25
4
How is concatenating two arrays the accepted answer for how to push one into another?! Those are two different operations.
– kaqqao
Mar 6 '17 at 19:18
|
show 4 more comments
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).
5
A better reference would be: developer.mozilla.org/en/JavaScript/Reference/Global_Objects/… [1]: developer.mozilla.org/en/JavaScript/Reference/Global_Objects/…
– Jamund Ferguson
Feb 23 '11 at 5:41
71
Slow though: jsperf.com/concat-vs-push-apply/10
– w00t
Aug 20 '12 at 19:42
11
I agree that performant execution is very nice. BUT isn't concat exactly for that purpose to concat to arrays? So it should be standard. Or is there other better things to do with concat? And it might be slow only because of bad implementation of the JS engine of the browser or wherever you're using it in? It might be fixed one day. I would choose code maintainability over hacky speed optimizations. Hmm ....
– Bitterblue
Jun 10 '16 at 9:04
1
Also I just benchmarked the situation: concat vs. push.apply.Google Chrome
: fast (concat = winner),Opera
: fast (concat = winner),IE
: slower (concat = winner),Firefox
: slow (push.apply = winner, yet 10 times slower than Chrome's concat) ... speak of bad JS engine implementation.
– Bitterblue
Jun 10 '16 at 9:25
4
How is concatenating two arrays the accepted answer for how to push one into another?! Those are two different operations.
– kaqqao
Mar 6 '17 at 19:18
|
show 4 more comments
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).
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).
edited Apr 22 '14 at 18:15
Tom Wadley
98.9k11928
98.9k11928
answered Nov 11 '10 at 15:37
WiseGuyEhWiseGuyEh
12.1k11620
12.1k11620
5
A better reference would be: developer.mozilla.org/en/JavaScript/Reference/Global_Objects/… [1]: developer.mozilla.org/en/JavaScript/Reference/Global_Objects/…
– Jamund Ferguson
Feb 23 '11 at 5:41
71
Slow though: jsperf.com/concat-vs-push-apply/10
– w00t
Aug 20 '12 at 19:42
11
I agree that performant execution is very nice. BUT isn't concat exactly for that purpose to concat to arrays? So it should be standard. Or is there other better things to do with concat? And it might be slow only because of bad implementation of the JS engine of the browser or wherever you're using it in? It might be fixed one day. I would choose code maintainability over hacky speed optimizations. Hmm ....
– Bitterblue
Jun 10 '16 at 9:04
1
Also I just benchmarked the situation: concat vs. push.apply.Google Chrome
: fast (concat = winner),Opera
: fast (concat = winner),IE
: slower (concat = winner),Firefox
: slow (push.apply = winner, yet 10 times slower than Chrome's concat) ... speak of bad JS engine implementation.
– Bitterblue
Jun 10 '16 at 9:25
4
How is concatenating two arrays the accepted answer for how to push one into another?! Those are two different operations.
– kaqqao
Mar 6 '17 at 19:18
|
show 4 more comments
5
A better reference would be: developer.mozilla.org/en/JavaScript/Reference/Global_Objects/… [1]: developer.mozilla.org/en/JavaScript/Reference/Global_Objects/…
– Jamund Ferguson
Feb 23 '11 at 5:41
71
Slow though: jsperf.com/concat-vs-push-apply/10
– w00t
Aug 20 '12 at 19:42
11
I agree that performant execution is very nice. BUT isn't concat exactly for that purpose to concat to arrays? So it should be standard. Or is there other better things to do with concat? And it might be slow only because of bad implementation of the JS engine of the browser or wherever you're using it in? It might be fixed one day. I would choose code maintainability over hacky speed optimizations. Hmm ....
– Bitterblue
Jun 10 '16 at 9:04
1
Also I just benchmarked the situation: concat vs. push.apply.Google Chrome
: fast (concat = winner),Opera
: fast (concat = winner),IE
: slower (concat = winner),Firefox
: slow (push.apply = winner, yet 10 times slower than Chrome's concat) ... speak of bad JS engine implementation.
– Bitterblue
Jun 10 '16 at 9:25
4
How is concatenating two arrays the accepted answer for how to push one into another?! Those are two different operations.
– kaqqao
Mar 6 '17 at 19:18
5
5
A better reference would be: developer.mozilla.org/en/JavaScript/Reference/Global_Objects/… [1]: developer.mozilla.org/en/JavaScript/Reference/Global_Objects/…
– Jamund Ferguson
Feb 23 '11 at 5:41
A better reference would be: developer.mozilla.org/en/JavaScript/Reference/Global_Objects/… [1]: developer.mozilla.org/en/JavaScript/Reference/Global_Objects/…
– Jamund Ferguson
Feb 23 '11 at 5:41
71
71
Slow though: jsperf.com/concat-vs-push-apply/10
– w00t
Aug 20 '12 at 19:42
Slow though: jsperf.com/concat-vs-push-apply/10
– w00t
Aug 20 '12 at 19:42
11
11
I agree that performant execution is very nice. BUT isn't concat exactly for that purpose to concat to arrays? So it should be standard. Or is there other better things to do with concat? And it might be slow only because of bad implementation of the JS engine of the browser or wherever you're using it in? It might be fixed one day. I would choose code maintainability over hacky speed optimizations. Hmm ....
– Bitterblue
Jun 10 '16 at 9:04
I agree that performant execution is very nice. BUT isn't concat exactly for that purpose to concat to arrays? So it should be standard. Or is there other better things to do with concat? And it might be slow only because of bad implementation of the JS engine of the browser or wherever you're using it in? It might be fixed one day. I would choose code maintainability over hacky speed optimizations. Hmm ....
– Bitterblue
Jun 10 '16 at 9:04
1
1
Also I just benchmarked the situation: concat vs. push.apply.
Google Chrome
: fast (concat = winner), Opera
: fast (concat = winner), IE
: slower (concat = winner), Firefox
: slow (push.apply = winner, yet 10 times slower than Chrome's concat) ... speak of bad JS engine implementation.– Bitterblue
Jun 10 '16 at 9:25
Also I just benchmarked the situation: concat vs. push.apply.
Google Chrome
: fast (concat = winner), Opera
: fast (concat = winner), IE
: slower (concat = winner), Firefox
: slow (push.apply = winner, yet 10 times slower than Chrome's concat) ... speak of bad JS engine implementation.– Bitterblue
Jun 10 '16 at 9:25
4
4
How is concatenating two arrays the accepted answer for how to push one into another?! Those are two different operations.
– kaqqao
Mar 6 '17 at 19:18
How is concatenating two arrays the accepted answer for how to push one into another?! Those are two different operations.
– kaqqao
Mar 6 '17 at 19:18
|
show 4 more comments
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 https://stackoverflow.com/a/17368101/96100 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]);
}
};
8
note:newArray.push.apply(newArray, dataArray1);
gives the same asArray.prototype.push.applay(newArray,dataArra1);
– user669677
Jul 5 '13 at 11:02
Is this compatible with older browsers?
– Damien Ó Ceallaigh
Apr 6 '18 at 0:53
developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
– Damien Ó Ceallaigh
Apr 6 '18 at 0:53
1
@DamienÓCeallaigh: Yes. This is all compatible with browsers going back to IE 6 and even earlier.
– Tim Down
Apr 9 '18 at 11:16
This is the epitome of poor programming practices.Array.prototype.concat
is not bad, rather it is simply misunderstood and sometimes misused. Under these circumstances, it is only misunderstood, but not misused.
– Jack Giffin
Aug 15 '18 at 10:23
|
show 3 more comments
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 https://stackoverflow.com/a/17368101/96100 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]);
}
};
8
note:newArray.push.apply(newArray, dataArray1);
gives the same asArray.prototype.push.applay(newArray,dataArra1);
– user669677
Jul 5 '13 at 11:02
Is this compatible with older browsers?
– Damien Ó Ceallaigh
Apr 6 '18 at 0:53
developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
– Damien Ó Ceallaigh
Apr 6 '18 at 0:53
1
@DamienÓCeallaigh: Yes. This is all compatible with browsers going back to IE 6 and even earlier.
– Tim Down
Apr 9 '18 at 11:16
This is the epitome of poor programming practices.Array.prototype.concat
is not bad, rather it is simply misunderstood and sometimes misused. Under these circumstances, it is only misunderstood, but not misused.
– Jack Giffin
Aug 15 '18 at 10:23
|
show 3 more comments
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 https://stackoverflow.com/a/17368101/96100 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]);
}
};
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 https://stackoverflow.com/a/17368101/96100 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]);
}
};
edited May 23 '17 at 11:47
Community♦
11
11
answered Nov 11 '10 at 15:38
Tim DownTim Down
250k56375463
250k56375463
8
note:newArray.push.apply(newArray, dataArray1);
gives the same asArray.prototype.push.applay(newArray,dataArra1);
– user669677
Jul 5 '13 at 11:02
Is this compatible with older browsers?
– Damien Ó Ceallaigh
Apr 6 '18 at 0:53
developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
– Damien Ó Ceallaigh
Apr 6 '18 at 0:53
1
@DamienÓCeallaigh: Yes. This is all compatible with browsers going back to IE 6 and even earlier.
– Tim Down
Apr 9 '18 at 11:16
This is the epitome of poor programming practices.Array.prototype.concat
is not bad, rather it is simply misunderstood and sometimes misused. Under these circumstances, it is only misunderstood, but not misused.
– Jack Giffin
Aug 15 '18 at 10:23
|
show 3 more comments
8
note:newArray.push.apply(newArray, dataArray1);
gives the same asArray.prototype.push.applay(newArray,dataArra1);
– user669677
Jul 5 '13 at 11:02
Is this compatible with older browsers?
– Damien Ó Ceallaigh
Apr 6 '18 at 0:53
developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
– Damien Ó Ceallaigh
Apr 6 '18 at 0:53
1
@DamienÓCeallaigh: Yes. This is all compatible with browsers going back to IE 6 and even earlier.
– Tim Down
Apr 9 '18 at 11:16
This is the epitome of poor programming practices.Array.prototype.concat
is not bad, rather it is simply misunderstood and sometimes misused. Under these circumstances, it is only misunderstood, but not misused.
– Jack Giffin
Aug 15 '18 at 10:23
8
8
note:
newArray.push.apply(newArray, dataArray1);
gives the same as Array.prototype.push.applay(newArray,dataArra1);
– user669677
Jul 5 '13 at 11:02
note:
newArray.push.apply(newArray, dataArray1);
gives the same as Array.prototype.push.applay(newArray,dataArra1);
– user669677
Jul 5 '13 at 11:02
Is this compatible with older browsers?
– Damien Ó Ceallaigh
Apr 6 '18 at 0:53
Is this compatible with older browsers?
– Damien Ó Ceallaigh
Apr 6 '18 at 0:53
developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
– Damien Ó Ceallaigh
Apr 6 '18 at 0:53
developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
– Damien Ó Ceallaigh
Apr 6 '18 at 0:53
1
1
@DamienÓCeallaigh: Yes. This is all compatible with browsers going back to IE 6 and even earlier.
– Tim Down
Apr 9 '18 at 11:16
@DamienÓCeallaigh: Yes. This is all compatible with browsers going back to IE 6 and even earlier.
– Tim Down
Apr 9 '18 at 11:16
This is the epitome of poor programming practices.
Array.prototype.concat
is not bad, rather it is simply misunderstood and sometimes misused. Under these circumstances, it is only misunderstood, but not misused.– Jack Giffin
Aug 15 '18 at 10:23
This is the epitome of poor programming practices.
Array.prototype.concat
is not bad, rather it is simply misunderstood and sometimes misused. Under these circumstances, it is only misunderstood, but not misused.– Jack Giffin
Aug 15 '18 at 10:23
|
show 3 more comments
I will add one more "future-proof" reply
In ECMAScript 6, you can use the spread operator:
var arr1 = [0, 1, 2];
var arr2 = [3, 4, 5];
arr1.push(...arr2);
Spread operator is not yet included in all major browsers. For the current compatibility, see this (continuously updated) compatibility table.
You can, however, use spread operator with Babel.js.
edit:
See Jack Giffin reply below for more comments on performance. It seems concat is still better and faster than spread operator.
3
You can also use the spread operator if you are using TypeScript. If you target ES5, it will compile tonewArray.apply(newArray, dataArray1)
.
– AJ Richardson
Feb 26 '16 at 21:28
4
Note: if you need the result in a third array (thus not modifying arr1, as the initial question seemed to require), you can do newArray = [...arr1, ...arr2]
– dim
Sep 29 '17 at 19:42
Oh I didn't know that. Thanks. I have added an edit comment.
– Karel Bílek
Aug 17 '18 at 5:47
Similar to how concat would function then, with the bonus of being persistent (mutating the original array).
– robertmylne
Sep 1 '18 at 8:37
@robertmylne The spread operator obviously does not modify the original array, instead creating a new copy of all the arrays contents desparsed.
– Jack Giffin
Nov 20 '18 at 2:44
add a comment |
I will add one more "future-proof" reply
In ECMAScript 6, you can use the spread operator:
var arr1 = [0, 1, 2];
var arr2 = [3, 4, 5];
arr1.push(...arr2);
Spread operator is not yet included in all major browsers. For the current compatibility, see this (continuously updated) compatibility table.
You can, however, use spread operator with Babel.js.
edit:
See Jack Giffin reply below for more comments on performance. It seems concat is still better and faster than spread operator.
3
You can also use the spread operator if you are using TypeScript. If you target ES5, it will compile tonewArray.apply(newArray, dataArray1)
.
– AJ Richardson
Feb 26 '16 at 21:28
4
Note: if you need the result in a third array (thus not modifying arr1, as the initial question seemed to require), you can do newArray = [...arr1, ...arr2]
– dim
Sep 29 '17 at 19:42
Oh I didn't know that. Thanks. I have added an edit comment.
– Karel Bílek
Aug 17 '18 at 5:47
Similar to how concat would function then, with the bonus of being persistent (mutating the original array).
– robertmylne
Sep 1 '18 at 8:37
@robertmylne The spread operator obviously does not modify the original array, instead creating a new copy of all the arrays contents desparsed.
– Jack Giffin
Nov 20 '18 at 2:44
add a comment |
I will add one more "future-proof" reply
In ECMAScript 6, you can use the spread operator:
var arr1 = [0, 1, 2];
var arr2 = [3, 4, 5];
arr1.push(...arr2);
Spread operator is not yet included in all major browsers. For the current compatibility, see this (continuously updated) compatibility table.
You can, however, use spread operator with Babel.js.
edit:
See Jack Giffin reply below for more comments on performance. It seems concat is still better and faster than spread operator.
I will add one more "future-proof" reply
In ECMAScript 6, you can use the spread operator:
var arr1 = [0, 1, 2];
var arr2 = [3, 4, 5];
arr1.push(...arr2);
Spread operator is not yet included in all major browsers. For the current compatibility, see this (continuously updated) compatibility table.
You can, however, use spread operator with Babel.js.
edit:
See Jack Giffin reply below for more comments on performance. It seems concat is still better and faster than spread operator.
edited Aug 17 '18 at 5:47
community wiki
4 revs, 3 users 70%
Karel Bílek
3
You can also use the spread operator if you are using TypeScript. If you target ES5, it will compile tonewArray.apply(newArray, dataArray1)
.
– AJ Richardson
Feb 26 '16 at 21:28
4
Note: if you need the result in a third array (thus not modifying arr1, as the initial question seemed to require), you can do newArray = [...arr1, ...arr2]
– dim
Sep 29 '17 at 19:42
Oh I didn't know that. Thanks. I have added an edit comment.
– Karel Bílek
Aug 17 '18 at 5:47
Similar to how concat would function then, with the bonus of being persistent (mutating the original array).
– robertmylne
Sep 1 '18 at 8:37
@robertmylne The spread operator obviously does not modify the original array, instead creating a new copy of all the arrays contents desparsed.
– Jack Giffin
Nov 20 '18 at 2:44
add a comment |
3
You can also use the spread operator if you are using TypeScript. If you target ES5, it will compile tonewArray.apply(newArray, dataArray1)
.
– AJ Richardson
Feb 26 '16 at 21:28
4
Note: if you need the result in a third array (thus not modifying arr1, as the initial question seemed to require), you can do newArray = [...arr1, ...arr2]
– dim
Sep 29 '17 at 19:42
Oh I didn't know that. Thanks. I have added an edit comment.
– Karel Bílek
Aug 17 '18 at 5:47
Similar to how concat would function then, with the bonus of being persistent (mutating the original array).
– robertmylne
Sep 1 '18 at 8:37
@robertmylne The spread operator obviously does not modify the original array, instead creating a new copy of all the arrays contents desparsed.
– Jack Giffin
Nov 20 '18 at 2:44
3
3
You can also use the spread operator if you are using TypeScript. If you target ES5, it will compile to
newArray.apply(newArray, dataArray1)
.– AJ Richardson
Feb 26 '16 at 21:28
You can also use the spread operator if you are using TypeScript. If you target ES5, it will compile to
newArray.apply(newArray, dataArray1)
.– AJ Richardson
Feb 26 '16 at 21:28
4
4
Note: if you need the result in a third array (thus not modifying arr1, as the initial question seemed to require), you can do newArray = [...arr1, ...arr2]
– dim
Sep 29 '17 at 19:42
Note: if you need the result in a third array (thus not modifying arr1, as the initial question seemed to require), you can do newArray = [...arr1, ...arr2]
– dim
Sep 29 '17 at 19:42
Oh I didn't know that. Thanks. I have added an edit comment.
– Karel Bílek
Aug 17 '18 at 5:47
Oh I didn't know that. Thanks. I have added an edit comment.
– Karel Bílek
Aug 17 '18 at 5:47
Similar to how concat would function then, with the bonus of being persistent (mutating the original array).
– robertmylne
Sep 1 '18 at 8:37
Similar to how concat would function then, with the bonus of being persistent (mutating the original array).
– robertmylne
Sep 1 '18 at 8:37
@robertmylne The spread operator obviously does not modify the original array, instead creating a new copy of all the arrays contents desparsed.
– Jack Giffin
Nov 20 '18 at 2:44
@robertmylne The spread operator obviously does not modify the original array, instead creating a new copy of all the arrays contents desparsed.
– Jack Giffin
Nov 20 '18 at 2:44
add a comment |
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"]
This is not what the question was asking for. The question is asking for a way to create a new array each time, not modify an old array.
– Jack Giffin
Aug 15 '18 at 9:16
add a comment |
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"]
This is not what the question was asking for. The question is asking for a way to create a new array each time, not modify an old array.
– Jack Giffin
Aug 15 '18 at 9:16
add a comment |
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"]
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"]
edited Jul 9 '16 at 16:18
answered Sep 10 '15 at 21:12
Believe2014Believe2014
2,82011833
2,82011833
This is not what the question was asking for. The question is asking for a way to create a new array each time, not modify an old array.
– Jack Giffin
Aug 15 '18 at 9:16
add a comment |
This is not what the question was asking for. The question is asking for a way to create a new array each time, not modify an old array.
– Jack Giffin
Aug 15 '18 at 9:16
This is not what the question was asking for. The question is asking for a way to create a new array each time, not modify an old array.
– Jack Giffin
Aug 15 '18 at 9:16
This is not what the question was asking for. The question is asking for a way to create a new array each time, not modify an old array.
– Jack Giffin
Aug 15 '18 at 9:16
add a comment |
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 ?
add a comment |
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 ?
add a comment |
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 ?
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 ?
answered Nov 11 '10 at 15:37
Sébastien VINCENTSébastien VINCENT
971511
971511
add a comment |
add a comment |
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
Is also mentioned here at MDN as an example for "Merging two arrays"
– Wilt
Apr 27 '18 at 15:48
add a comment |
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
Is also mentioned here at MDN as an example for "Merging two arrays"
– Wilt
Apr 27 '18 at 15:48
add a comment |
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)
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)
edited Mar 19 '18 at 13:58
answered Apr 11 '16 at 4:32
shauncshaunc
2,7371935
2,7371935
1
Is also mentioned here at MDN as an example for "Merging two arrays"
– Wilt
Apr 27 '18 at 15:48
add a comment |
1
Is also mentioned here at MDN as an example for "Merging two arrays"
– Wilt
Apr 27 '18 at 15:48
1
1
Is also mentioned here at MDN as an example for "Merging two arrays"
– Wilt
Apr 27 '18 at 15:48
Is also mentioned here at MDN as an example for "Merging two arrays"
– Wilt
Apr 27 '18 at 15:48
add a comment |
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]
add a comment |
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]
add a comment |
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]
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]
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]
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]
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]
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]
edited Sep 23 '17 at 1:14
answered Jul 3 '17 at 1:36
Stephen QuanStephen Quan
11.4k25054
11.4k25054
add a comment |
add a comment |
The 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 | 66
where
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
This question is looking for a way to create a new array each time, not modify an existing array.
– Jack Giffin
Aug 15 '18 at 9:17
add a comment |
The 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 | 66
where
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
This question is looking for a way to create a new array each time, not modify an existing array.
– Jack Giffin
Aug 15 '18 at 9:17
add a comment |
The 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 | 66
where
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
The 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 | 66
where
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
answered May 20 '17 at 15:01
Panos TheofPanos Theof
1,05411923
1,05411923
This question is looking for a way to create a new array each time, not modify an existing array.
– Jack Giffin
Aug 15 '18 at 9:17
add a comment |
This question is looking for a way to create a new array each time, not modify an existing array.
– Jack Giffin
Aug 15 '18 at 9:17
This question is looking for a way to create a new array each time, not modify an existing array.
– Jack Giffin
Aug 15 '18 at 9:17
This question is looking for a way to create a new array each time, not modify an existing array.
– Jack Giffin
Aug 15 '18 at 9:17
add a comment |
With 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.
2
If you take a look at how babel converts it, you'll see that it should not be any slower than usingArray.push.apply
technique.
– emil.c
Dec 11 '17 at 9:19
1
@JackGiffin I was just referring to what Ryan mentioned that he doesn't know how it works internally and what are performance implications, I wasn't actually suggesting this approach. In any case, you've done a very good job on your answer, nice research, it's always good to know such details.
– emil.c
Nov 22 '18 at 19:50
add a comment |
With 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.
2
If you take a look at how babel converts it, you'll see that it should not be any slower than usingArray.push.apply
technique.
– emil.c
Dec 11 '17 at 9:19
1
@JackGiffin I was just referring to what Ryan mentioned that he doesn't know how it works internally and what are performance implications, I wasn't actually suggesting this approach. In any case, you've done a very good job on your answer, nice research, it's always good to know such details.
– emil.c
Nov 22 '18 at 19:50
add a comment |
With 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.
With 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.
edited Oct 25 '18 at 15:23
answered Jun 29 '16 at 18:24
Ryan H.Ryan H.
2,3392130
2,3392130
2
If you take a look at how babel converts it, you'll see that it should not be any slower than usingArray.push.apply
technique.
– emil.c
Dec 11 '17 at 9:19
1
@JackGiffin I was just referring to what Ryan mentioned that he doesn't know how it works internally and what are performance implications, I wasn't actually suggesting this approach. In any case, you've done a very good job on your answer, nice research, it's always good to know such details.
– emil.c
Nov 22 '18 at 19:50
add a comment |
2
If you take a look at how babel converts it, you'll see that it should not be any slower than usingArray.push.apply
technique.
– emil.c
Dec 11 '17 at 9:19
1
@JackGiffin I was just referring to what Ryan mentioned that he doesn't know how it works internally and what are performance implications, I wasn't actually suggesting this approach. In any case, you've done a very good job on your answer, nice research, it's always good to know such details.
– emil.c
Nov 22 '18 at 19:50
2
2
If you take a look at how babel converts it, you'll see that it should not be any slower than using
Array.push.apply
technique.– emil.c
Dec 11 '17 at 9:19
If you take a look at how babel converts it, you'll see that it should not be any slower than using
Array.push.apply
technique.– emil.c
Dec 11 '17 at 9:19
1
1
@JackGiffin I was just referring to what Ryan mentioned that he doesn't know how it works internally and what are performance implications, I wasn't actually suggesting this approach. In any case, you've done a very good job on your answer, nice research, it's always good to know such details.
– emil.c
Nov 22 '18 at 19:50
@JackGiffin I was just referring to what Ryan mentioned that he doesn't know how it works internally and what are performance implications, I wasn't actually suggesting this approach. In any case, you've done a very good job on your answer, nice research, it's always good to know such details.
– emil.c
Nov 22 '18 at 19:50
add a comment |
Here'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)
Hey budd there was a reason to develop and surely the reason wasn't speed . Speed matters when you have quite large array in that case concat is better
– Black Mamba
Nov 20 '18 at 3:37
add a comment |
Here'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)
Hey budd there was a reason to develop and surely the reason wasn't speed . Speed matters when you have quite large array in that case concat is better
– Black Mamba
Nov 20 '18 at 3:37
add a comment |
Here'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)
Here'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)
var newArray = ;
let dataArray1 = [1,2,3,4]
let dataArray2 = [5,6,7,8]
newArray = [...dataArray1, ...dataArray2]
console.log(newArray)
var newArray = ;
let dataArray1 = [1,2,3,4]
let dataArray2 = [5,6,7,8]
newArray = [...dataArray1, ...dataArray2]
console.log(newArray)
let dataArray1 = [1,2,3,4]
let dataArray2 = [5,6,7,8]
let newArray = dataArray1.concat(dataArray2);
console.log(newArray)
let dataArray1 = [1,2,3,4]
let dataArray2 = [5,6,7,8]
let newArray = dataArray1.concat(dataArray2);
console.log(newArray)
edited Nov 20 '18 at 6:46
answered Jun 15 '18 at 5:10
Black MambaBlack Mamba
2,78912139
2,78912139
Hey budd there was a reason to develop and surely the reason wasn't speed . Speed matters when you have quite large array in that case concat is better
– Black Mamba
Nov 20 '18 at 3:37
add a comment |
Hey budd there was a reason to develop and surely the reason wasn't speed . Speed matters when you have quite large array in that case concat is better
– Black Mamba
Nov 20 '18 at 3:37
Hey budd there was a reason to develop and surely the reason wasn't speed . Speed matters when you have quite large array in that case concat is better
– Black Mamba
Nov 20 '18 at 3:37
Hey budd there was a reason to develop and surely the reason wasn't speed . Speed matters when you have quite large array in that case concat is better
– Black Mamba
Nov 20 '18 at 3:37
add a comment |
Research And Results
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.
The Future
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.
Clarifications
Spare Arrays
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"];
Array-Likes
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 slice function argument 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}() ));
add a comment |
Research And Results
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.
The Future
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.
Clarifications
Spare Arrays
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"];
Array-Likes
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 slice function argument 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}() ));
add a comment |
Research And Results
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.
The Future
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.
Clarifications
Spare Arrays
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"];
Array-Likes
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 slice function argument 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}() ));
Research And Results
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.
The Future
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.
Clarifications
Spare Arrays
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"];
Array-Likes
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 slice function argument 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}() ));
// 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]);
// 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]);
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}() ));
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}() ));
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 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}() ));
edited Nov 22 '18 at 14:22
answered Aug 15 '18 at 14:43
Jack GiffinJack Giffin
1,032925
1,032925
add a comment |
add a comment |
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
Please don't just post code as an answer. Explain what the code does and how it solves the problem.
– Patrick Hund
Jun 7 '17 at 18:28
add a comment |
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
Please don't just post code as an answer. Explain what the code does and how it solves the problem.
– Patrick Hund
Jun 7 '17 at 18:28
add a comment |
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' ]
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' ]
edited Jan 9 '18 at 7:02
answered Jun 7 '17 at 14:33
KARTHIKEYAN.AKARTHIKEYAN.A
5,13534054
5,13534054
1
Please don't just post code as an answer. Explain what the code does and how it solves the problem.
– Patrick Hund
Jun 7 '17 at 18:28
add a comment |
1
Please don't just post code as an answer. Explain what the code does and how it solves the problem.
– Patrick Hund
Jun 7 '17 at 18:28
1
1
Please don't just post code as an answer. Explain what the code does and how it solves the problem.
– Patrick Hund
Jun 7 '17 at 18:28
Please don't just post code as an answer. Explain what the code does and how it solves the problem.
– Patrick Hund
Jun 7 '17 at 18:28
add a comment |
instead of push() function use concat function for IE. example,
var a=a.concat(a,new Array('amin'));
both are very IE compatible
– Jack Giffin
Aug 16 '18 at 8:38
add a comment |
instead of push() function use concat function for IE. example,
var a=a.concat(a,new Array('amin'));
both are very IE compatible
– Jack Giffin
Aug 16 '18 at 8:38
add a comment |
instead of push() function use concat function for IE. example,
var a=a.concat(a,new Array('amin'));
instead of push() function use concat function for IE. example,
var a=a.concat(a,new Array('amin'));
answered Dec 27 '13 at 1:06
user1911703user1911703
3294620
3294620
both are very IE compatible
– Jack Giffin
Aug 16 '18 at 8:38
add a comment |
both are very IE compatible
– Jack Giffin
Aug 16 '18 at 8:38
both are very IE compatible
– Jack Giffin
Aug 16 '18 at 8:38
both are very IE compatible
– Jack Giffin
Aug 16 '18 at 8:38
add a comment |
Т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))}
add a comment |
Т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))}
add a comment |
Т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))}
Т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))}
answered Dec 12 '14 at 12:31
user4354031user4354031
21
21
add a comment |
add a comment |
Most simple:
var newArray = dataArray1.slice(0);
1
This does not cover the problem in the question: concatenating two arrays.
– frasertweedale
May 8 '15 at 9:40
How does this try to answer the question?
– user6490459
Jan 30 at 15:05
add a comment |
Most simple:
var newArray = dataArray1.slice(0);
1
This does not cover the problem in the question: concatenating two arrays.
– frasertweedale
May 8 '15 at 9:40
How does this try to answer the question?
– user6490459
Jan 30 at 15:05
add a comment |
Most simple:
var newArray = dataArray1.slice(0);
Most simple:
var newArray = dataArray1.slice(0);
answered May 8 '15 at 9:36
PhuLuongPhuLuong
463311
463311
1
This does not cover the problem in the question: concatenating two arrays.
– frasertweedale
May 8 '15 at 9:40
How does this try to answer the question?
– user6490459
Jan 30 at 15:05
add a comment |
1
This does not cover the problem in the question: concatenating two arrays.
– frasertweedale
May 8 '15 at 9:40
How does this try to answer the question?
– user6490459
Jan 30 at 15:05
1
1
This does not cover the problem in the question: concatenating two arrays.
– frasertweedale
May 8 '15 at 9:40
This does not cover the problem in the question: concatenating two arrays.
– frasertweedale
May 8 '15 at 9:40
How does this try to answer the question?
– user6490459
Jan 30 at 15:05
How does this try to answer the question?
– user6490459
Jan 30 at 15:05
add a comment |
protected by T J Jan 4 '16 at 17:12
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
See this url stackoverflow.com/questions/351409/appending-to-array
– Jakir Hossain
Jan 10 '16 at 10:50
This should be the answer davidwalsh.name/combining-js-arrays
– starikovs
Sep 22 '17 at 8:24