Several methods of JS merging arrays and their pros and cons comparison

Source: Internet
Author: User

This article mainly introduces the JS merged array of several methods and pros and cons comparison, this article explains the concat, loop insertion, reduce and other methods combined arrays, and their pros and cons to do a comparison, the need for friends can refer to the next

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:

The code is as follows:

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:

The code is as follows:
[
5, 5, 1, 9, 9, 6, 4, 5, 8,
"Tie", "Mao", "Csdn", "Ren", "Fu", "Fei"
]

Concat (..) Method

The most common usage is as follows:

The code 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, C is a whole new array that represents the combination of the two arrays, Q and B, but Q and B are useless now, right?

If the Q array has 10,000 elements, the B array also has 10,000 elements? Then the array c now has 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!

The code is as follows:


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 the Array#push () method:

The code is as follows:


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 what if the Q array is small and B is large? For memory and speed considerations, you want to insert the smaller q in front of B. No problem, just use the Unshift () method instead of push (), and corresponding to the large-to-small loop traversal: The code is as follows:


' 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 Array#reduce first:

The code is as follows:


' 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 () are very tall, but they are a bit bulky, and the average person can't remember. The + arrow function (arrow-functions) in JS Specification 6 can greatly reduce the amount of code, but it is also a waste of the way to perform function calls on each array element.
So what about the code below?

The code is as follows:


' 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? In particular, the Unshift () method does 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 apply () as the second argument (the first parameter in the Apply mode calls the function when it becomes this, that is, context, scope), or use ... The way the operator is expanded, the array is actually broken into the arguments of the function.
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, either push () or unshift () calls. This method is only available for thousands of elements, so it must be limited to a certain range.

Note: You can also try splice () and will definitely find him and push (..) /unshift (..) are all the same restrictions.

One option is to continue with this approach, but in batches:

The code is as follows:


function Combineinto (q,b) {
var len = q.length;
for (var i=0; i < Len; i=i+5000) {
Handling 5,000 records at a time
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.

Summarize

Array#concat () is a proven 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.

Reprint: http://www.jb51.net/article/55364.htm

Several methods of JS merging arrays and their pros and cons comparison

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.