Several methods and advantages and disadvantages of JS merging arrays _ Basics

Source: Internet
Author: User

This article is the basic skill of JavaScript. We will learn the various common methods of combining/merging two JS arrays and compare the pros and cons of each method.

Let's take a look at the specific scenario:

Copy Code code 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 the simple concatenation of the array Q and B is:

Copy Code code 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:

Copy Code code 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 Q and B, but Q and B are useless now, right?

If the Q array has 10,000 elements, B arrays also have 10,000 elements? Then array c now has 20,000 elements, which takes up twice times of memory.

"That's no problem!", you might think. Just put Q and B on the line, and then it will be garbage collected, right? The problem is solved!

Copy Code code as follows:

Q = b = null; ' Q ' and ' B ' can now be reclaimed by garbage.

Amount? If the array is very small, then naturally no problem. But when it comes to large arrays or requiring multiple repetitions, memory is limited, and it needs to be optimized.

Looping insert

OK, let's add the contents of one array to the other and try using the Array#push () method:

Copy Code code as follows:

Insert 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 holds the contents of two original arrays (q + b).

It seems to do a good job of memory optimization.

But what if the Q array is small and B is big? For memory and speed considerations, you want to insert the smaller q ahead of B. No problem, as long as the Unshift () method instead of push () can be, the corresponding also from large to small to cycle through:

Copy Code code 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:

Copy Code code 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 tall, but a little 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 very good way to perform function calls on each array element.
So what about the following code?

Copy Code code 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 high-end: A.push (... b) or b.unshift (... a)

But, in fact, this approach is still too optimistic. In both cases, whether a or B is passed to apply () as the second argument (the first argument inside becomes this when the function is invoked, i.e., context, scope), or use ... The way in which operators are expanded, in fact arrays are broken down into arguments of functions.
The first major problem is that it takes up double the memory (of course, it's temporary!) because you need to copy the array into the stack of functions. In addition, different JS engines have different implementation algorithms, which may limit the number of parameters the function can pass.

If the array adds 1 million elements, it will certainly exceed the allowable size of the function stack, whether 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 be sure to find him and push (..) /unshift (..) are the same restrictions.

One option is to continue using this method, but to use batch processing:

Copy Code code as follows:

function Combineinto (q,b) {
var len = q.length;
for (Var i=0 i < Len; i=i+5000) {
Handle 5,000 records at a time
B.unshift.apply (b, Q.slice (I, i+5000));
}
}

And so on, we've compromised the readability of the code (even the performance!). Let's end this journey before we give up.

Summarize

Array#concat () is a time-tested method for combining two (or more) arrays. But he created a new array instead of modifying an existing one.

There are a lot of alternative methods, but they all have different advantages and disadvantages, need to choose according to the actual situation.

The advantages/disadvantages are listed above, and 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.

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.