Original link: combining JS Arrays
Original Date: 2014-09-09
Translation Date: 2014-09-18
Translators: Anchor
This article belongs to JavaScript's basic skills. We will learn to combine/combine the various regular usages of two JS arrays and compare the pros and cons of various methods.
Let's take a look at the detailed scenario first:
var q = [5, 5, 1, 9, 9, 6, 4, 5, 8];var b = ["Tie", "Mao", "Csdn", "Ren", "Fu", "Fei"];
It is very obvious that the result of simple concatenation of arrays Q and B is:
[ 5, 5, 1, 9, 9, 6, 4, 5, 8, "Tie", "Mao", "Csdn", "Ren", "Fu", "Fei"]
concat (..) Method
The most common uses are as follows:
var C = Q.concat (b); q; [5,5,1,9,9,6,4,5,8]b; ["Tie", "Mao", "Csdn", "Ren", "Fu", "Fei"];C; [5,5,1,9,9,6,4,5,8, "Tie", "Mao", "Csdn", "Ren", "Fu", "Fei")
As you can see,
Cis a brand-new array that represents
QAnd
bThe combination of these two arrays, but
QAnd
bIt's useless now, isn't it?
Assume
QArray has
10000Elements,
bArrays are also available with
10000An element? Then the array
CNow there are 20,000 elements, which take up twice times the memory.
"That's no problem!", you might think. Just leave Q and b empty, and then you'll be garbage collected, right? The problem has been overcome!
Q = b = null; ' Q ' and ' B ' can now be garbage collected
Amount?
Assuming that the arrays are very small, it is natural that there is no problem. But for large arrays, or multiple iterations, memory is limited and it needs to be optimized.
Loop insert
OK, let's add the contents of an array to the other one and try using the Array#push () method:
Insert the array ' B ' into ' Q ' for (var i=0; i < b.length; i++) { q.push (b[i]);} Q [5,5,1,9,9,6,4,5,8, "Tie", "Mao", "Csdn", "Ren", "Fu", "fei"]b = null;
Today, Q stores the contents of two original arrays (q + b).
It seems to be doing a good job of memory optimization.
But suppose
QArrays are very small and
bIt's very big? For memory and speed considerations, you want to put the smaller
QInsert to
bFront. No problem, just use
unshift ()method to replace
push (), the corresponding also to be from large to small loop traversal:
' Q ' into ' B ': for (var i=q.length-1; I >= 0; i--) { b.unshift (q[i]);} b [5,5,1,9,9,6,4,5,8, "Tie", "Mao", "Csdn", "Ren", "Fu", "fei"]q = null;
Useful Tips
Sadly, the for loop is very earthy and difficult to maintain. Can we do better?
Let's try it first.
Array#reduce:
' B ' onto ' q ': q = b.reduce (function (coll,item) { Coll.push (item); return coll;}, q); q; [5,5,1,9,9,6,4,5,8, "Tie", "Mao", "Csdn", "Ren", "Fu", "Fei"]//or ' Q ' into ' B ': b = q.reduceright (function (Coll,item) { Coll.unshift (item); return coll;}, b); b; [5,5,1,9,9,6,4,5,8, "Tie", "Mao", "Csdn", "Ren", "Fu", "Fei")
array#reduce ()And
array#reduceright ()Very tall, but a bit bulky, and the average person also can't remember. JS Specification 6
=The arrow function (arrow-functions) can greatly reduce the amount of code, but the need to run function calls to each array of elements is also a very slag.
So what about the following code?
' B ' onto ' Q ': q.push.apply (q, b); q; [5,5,1,9,9,6,4,5,8, "Tie", "Mao", "Csdn", "Ren", "Fu", "Fei"]//or ' Q ' into ' B ': b.unshift.apply (b, q); b; [5,5,1,9,9,6,4,5,8, "Tie", "Mao", "Csdn", "Ren", "Fu", "Fei")
Big is taller, isn't it? Especially
unshift ()Methods do not need to consider the reverse order as before. ES6 expansion operator (spread operator, plus
...Prefix) is more advanced:
A.push (... b)Or
B.unshift (... a)
However, in fact, such a method is still too optimistic. In both cases, either a or B is passed to the
apply ()As the second parameter (Apply mode calls function when the first parameter changes internally to this, that is, context, contexts, scope), or use
...Expand the operator, in fact the array will be broken into a function
arguments.
The first basic problem is that it takes up double the memory (of course, it's temporary!), because you need to copy the array into the function stack. In addition, different JS engines have different implementation algorithms that may limit the number of parameters the function can pass.
Assuming that the array has 1 million elements added, it will certainly exceed the size agreed to by the function stack, whether it is
push ()Or
unshift ()Call. Such a method is only available for thousands of elements, so it must be limited to a certain range.
Note: You can also try
Splice (), would surely find him and
Push (..) /unshift (..)Are the same restrictions.
One option is to continue using this method, but with batch processing:
function Combineinto (q,b) { var len = q.length; for (var i=0; i < Len; i=i+5000) { //one-time processing 5,000 b.unshift.apply (b, Q.slice (I, i+5000));} }
Wait, we're hurting the readability of the code (even the performance!). Let's finish this journey before we give up.
Summary
Array#concat ()is a tried and tested method for combining two (or more) arrays. But he created a new array instead of altering the existing one.
There are a lot of flexible methods, but they have different advantages and disadvantages, need to choose according to the actual situation.
Here are a list of strengths/weaknesses, perhaps the best (including not listed) methods are
Reduce (..)And
reduceright (..)
Whatever you choose, you should think critically about your array merging strategy, rather than taking it for granted.
Comparison of various methods of JS merging arrays and their pros and cons