Comparison of various methods of JS merging arrays and their pros and cons

Source: Internet
Author: User

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 the various common methods of combining/merging two JS arrays, and compare the pros and cons of various methods.

Let's take a look at the specific scenario:
var q = [5, 5, 1, 9, 9, 6, 4, 5, 8];var b = ["Tie", "Mao", "Csdn", "Ren", "Fu", "Fei"];

Obviously, the result of a 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 usage is 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 doesn't work now, does it?
If QArray has 10000Elements, bArrays are also available with 10000An element? Then the array CNow there are 20,000 elements, which takes 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 is solved!
Q = b = null; ' Q ' and ' B ' can now be garbage collected
Amount? If the arrays are small, that's fine. But for large arrays, or when repeated processing is required, memory is limited and it needs to be optimized.

Loop Insert

OK, let's add the contents of one array to the other and try using 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;

Now, Q contains the contents of the two original array (q + b).
It seems to be doing a good job of memory optimization.
But if QArrays are small and bWhat's the big thing? For memory and speed considerations, you want to put the smaller QInsert to bFront. No problem, just use unshift ()Method instead push (), the corresponding also 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;

Practical Tips

The sad reminder is that 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 little cumbersome, and the average person can not remember. JS Specification 6 =The arrow function (arrow-functions) can greatly reduce the amount of code, but it is also a waste to perform function calls on each array element.
So what about the code below?
' 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)
But, in fact, this approach is still too optimistic. In both cases, either a or B is passed to the apply ()As the second argument (when you call function in the Apply mode, the first parameter changes internally to this, that is, context, scope), or use the ...Expand the operator, in fact the array will be broken into a function arguments.
The first major problem is that it takes up double the memory (of course, it's temporary!) because the array needs to be copied into the function stack. In addition, different JS engines have different implementation algorithms, which may limit the number of arguments the function can pass.
If the array adds 1 million elements, it will certainly exceed the size allowed by the function stack, whether push ()Or unshift ()Call. This 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 with this approach, but in batches:
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 instead of modifying an existing one, he creates a new array.
There are many flexible methods, but they all have different advantages and disadvantages, need to choose according to the actual situation.
There are various advantages/disadvantages listed above, 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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.