Comparison of several methods and advantages of JS array merging and several methods of js Array

Source: Internet
Author: User

Comparison of several methods and advantages of JS array merging and several methods of js Array

This article is a basic JavaScript skill. We will learn a variety of common methods to combine/merge two JS arrays, and compare the advantages and disadvantages of various methods.

Let's take a look at the specific scenarios:

Copy codeThe 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 array q and array B is:
Copy codeThe 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 codeThe Code is as follows:
Var c = q. concat (B );

Q; // [, 8]
B; // ["tie", "mao", "csdn", "ren", "fu", "fei"];

C; // [5, 5, 9, 6, 8, "tie", "mao", "csdn", "ren", "fu", "fei"]

As you can see, c is a brand new array, indicating the combination of q and B, but q and B are useless now, right?

If the q array has 10000 elements and the B array has 10000 elements? Array c now has 20000 elements, which occupies 2 times of memory.

"No problem !", You may think that, if q and B are left blank, they will be reclaimed, right? Problem solved!
Copy codeThe Code is as follows:
Q = B = null; // 'Q' and 'B' can be recycled now

Amount? If the array is small, there is no problem, but the memory is limited when large arrays or repeated processing is required, and it needs to be optimized.

Loop insert

OK. Let's add the content of an Array to another one. Use the Array # push () method:
Copy codeThe Code is as follows:
// Insert 'B' into 'Q'
For (var I = 0; I <B. length; I ++ ){
Q. push (B [I]);
}

Q; // [5, 5, 9, 6, 8, "tie", "mao", "csdn", "ren", "fu", "fei"]

B = null;

Now, q stores the content of two original arrays (q + B ).

It seems that the memory optimization is good.

But what if the q array is small and B is big? For the sake of memory and speed, we want to insert a smaller q to the front of B. no problem. You only need to use the unshift () method instead of the push () method. The corresponding loop traversal should also be performed from large to small:
Copy codeThe Code is as follows:
// 'Q' into 'B ':
For (var I = q. length-1; I> = 0; I --){
B. unshift (q [I]);
}

B; // [5, 5, 9, 6, 8, "tie", "mao", "csdn", "ren", "fu", "fei"]

Q = null;

Practical Skills

Sadly, the for loop is very earthy and difficult to maintain. Can we do better?
Let's first try Array # reduce:
Copy codeThe Code is as follows:
// 'B' onto 'q ':
Q = B. reduce (function (coll, item ){
Coll. push (item );
Return coll;
}, Q );

Q; // [5, 5, 9, 6, 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, 9, 6, 8, "tie", "mao", "csdn", "ren", "fu", "fei"]

Array # reduce () and Array # reduceRight () are very large, but they are a little bulky and hard to remember. in JS specification 6, the => arrow-functions function can greatly reduce the amount of code, but it is also a very scum to execute function calls for each array element.
What about the following code?
Copy codeThe Code is as follows:
// 'B' onto 'q ':
Q. push. apply (q, B );

Q; // [5, 5, 9, 6, 8, "tie", "mao", "csdn", "ren", "fu", "fei"]

// Or 'q' into 'B ':
B. unshift. apply (B, q );

B; // [5, 5, 9, 6, 8, "tie", "mao", "csdn", "ren", "fu", "fei"]

BIG is higher, right !? In particular, the unshift () method does not need to consider the reverse sequence as before. ES6 expansion operator (spread operator, plus... prefix) is even higher:. push (... b) or B. unshift (... a)

However, in fact, this method is too optimistic. in both cases, whether it is to pass a or B to apply () as the second parameter (when the Function is called in the apply method, the first parameter becomes this internally, that is, context, context, scope), or use... in fact, the array will be split into the arguments of the function.
The first major problem is that the memory usage doubles (of course, it's temporary !), 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 by the function.

If 1 million elements are added to the array, the size of the array must exceed the size allowed by the function stack, whether it is a 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 () and you will surely find that it is the same as push (...)/unshift.

One option is to continue using this method, but batch processing is adopted:
Copy codeThe Code is as follows:
Function combineInto (q, B ){
Var len = q. length;
For (var I = 0; I <len; I = I + 5000 ){
// Process 5000 entries at a time
B. unshift. apply (B, q. slice (I, I + 5000 ));
}
}

And so on. We damage the readability of the Code (or even the performance !). Let's end this journey before we give up.

Summary

Array # concat () is a tested method used to combine two (or more) arrays. but it creates a new Array instead of modifying an existing one.

There are many workarounds, but they all have different advantages and disadvantages and need to be selected based on the actual situation.

The advantages/disadvantages are listed above. Maybe the best (including those not listed) methods are reduce (...) and reduceRight (..)

Whatever you choose, you should think about your array merging strategy critically, instead of taking it for granted.


JS array Merging

This is an object, not an array.
It took me some time to write a function. Please add more points

<! -- Status OK -->
<! Doctype html public "-// W3C // dtd html 4.01 Transitional // EN">
<Html>
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = gb2312"/>
<Title> JS array merging question _ Baidu Knows </title>

<Link rel = "alternate" type = "application/rss + xml" title = "latest answer to" JS array merging question "(RSS 2.0)" href = "zhidao.baidu.com/..w.rssqb">

</Head>
<Body>
<Script>
Function objConcat (a1, a2 ){
Var newarr = {};
For (var k1 in a1 ){
Newarr [k1] = a1 [k1];
}
For (var k2 in a2 ){
Newarr [k2] = a2 [k2];
}
Return newarr;
}

Arr1 = {a: 1, B: 2, c: 3 };
Arr2 = {B: 5, h: 6, k: 7 };
Arr = objConcat (arr1, arr2 );
For (var key in arr ){
Document. write (key + '->' + arr [key] + '</br> ');
}
</Script>
</Body>
</Html>

In js, how does one combine the array content with two new Object arrays and repeat the content?

If it is a common data type, it is very simple

Var ARR1 = [1, 2, 4];
Var ARR2 = [3, 4, 5, 6];

Function mergeArray (arr1, arr2 ){
Var _ arr = [];
For (var I = 0; I <arr1.length; I ++ ){
_ Arr. push (arr1 [I]);
}
Var _ dup;
For (var I = 0; I <arr2.length; I ++ ){
_ Dup = false;
For (var _ I = 0; _ I <arr1.length; _ I ++ ){
If (arr2 [I] === arr1 [_ I]) {
_ Dup = true;
Break;
}
}
If (! _ Dup ){
_ Arr. push (arr2 [I]);
}
}

Return _ arr;
}

Var B = mergeArray (ARR1, ARR2 );
// B = [1, 2, 3, 4, 5, 6]
// The upstairs method returns ['1', '2', '3', '4', '5'] and converts it to a string.

If it is a complex object and an array, it is a little more troublesome and needs to be compared after serialization

Object. prototype. Serialize = function ()
{
Var type = _ typeof _ (this );
Switch (type)
{
Case 'array ':
{
Var strArray = '[';
For (var I = 0; I <this. length; ++ I)
{
Var value = '';
If (this [I])
{
Value = this [I]. Serialize ();
}
StrArray + = value + ',';
}
If (strArray. charAt (strArray. length-1) = ',')
{
StrArray = strArray. substr (0, strArray. length-1 );
}
StrArray + = ']';
Return strArray;
}
Case 'date ':
{
Return 'new Date ('+ this. getTime () + ')';
}
Case 'boolean ':
Case 'function ':
Case 'number ':
Case 'string ':
{
Return this. toString ();
}
Default:
{
Var serialize = '{';
For (var key in this)
{
If (key = 'serialize') continue;
Var subserialize = 'null ';
If (this [key]! = Undefined)
{
Subserialize = this [key]. Serialize ();
}
Serialize +... the remaining full text>

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.