Home > Web Front-end > JS Tutorial > Several methods of merging arrays in JS and comparison of advantages and disadvantages_Basic knowledge

Several methods of merging arrays in JS and comparison of advantages and disadvantages_Basic knowledge

WBOY
Release: 2016-05-16 16:35:59
Original
1420 people have browsed it

This article belongs to the basic skills of JavaScript. We will learn various common methods of combining/merging two JS arrays and compare the advantages and disadvantages of various methods.

Let’s take a look at the specific scenario first:

Copy code 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 simple concatenation of arrays q and b is:

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

Copy code 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 brand new array, representing 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, and the b array also has 10,000 elements? Then the array c now has 20,000 elements, and this method takes up twice the memory.

"That's no problem!", you may think. Just leave q and b empty, and then they will be garbage collected, right? Problem solved!

Copy code The code is as follows:

q = b = null; // `q` and `b` are now garbage collected

Um? If the arrays are small, then there is no problem. But for large arrays, or when repeated processing is required multiple times, the memory is limited, and it also needs to be optimized.

Loop insertion

OK, let’s try adding the contents of one array to another, using the Array#push() method:

Copy code The code is 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 stores the contents of two original arrays (q b).

It seems that the memory optimization has been done well.

But what if the q array is small and b is large? For the sake of memory and speed, you want to insert the smaller q in front of b. No problem, just use the unshift() method instead of push() That’s it, and the corresponding cycle needs to be traversed from large to small:

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

Sadly, for loops are boring and difficult to maintain. Can we do better?
Let’s try Array#reduce first:

Copy code 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 fancy, but a bit cumbersome, and most people can’t remember them. The => arrow-functions in JS specification 6 can greatly reduce the amount of code. , but it requires a function call for each array element, which is also a very poor method.
So what about the code below?

Copy code 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 higher, right!? Especially the unshift() method does not need to consider the reverse order as before. The ES6 spread operator (spread operator, plus... prefix) is even higher: a. push( ...b ) or b.unshift( ...a )

However, in fact this method is still too optimistic. In both cases, whether a or b is passed to apply() as the second parameter (the first parameter is internal when calling Function in apply mode Become this (i.e. context, context, scope), or use... the expansion operator. In fact, the array will be broken up into arguments of the function.
The first major problem is that it takes up double the memory (temporarily, of course!) because the array needs to be copied to the function stack. In addition, different JS engines have different implementation algorithms, which may limit The number of parameters that can be passed to the function.

If one million elements are added to the array, it will definitely exceed the size allowed by the function stack, regardless of push() or unshift() call. This method is only available when there are thousands of elements, so it must be limited It cannot exceed a certain range.

Note: You can also try splice(), and you will definitely find that it has the same restrictions as push(..)/unshift(..).

One option is to continue using this method, but in batches:

Copy code The code is as follows:

function combineInto(q,b) {
var len = q.length;
for (var i=0; i < len; i=i 5000) {
              // Process 5000 items at a time
b.unshift.apply( b, q.slice( i, i 5000 ) );
}
}

Wait, we’re hurting the readability of our code (and even performance!). Let’s end this journey before we give up.

Summary

Array#concat() is the tried and tested method for combining two (or more) arrays. But it creates a new array rather than modifying an existing one.

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

There are various advantages/disadvantages listed above, perhaps the best (including those not listed) are reduce(..) and reduceRight(..)

Whatever you choose, think critically about your array merging strategy and not take it for granted.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template