javascript merge two arrays

In the process of development, we often encounter situations where we need to combine two arrays into one array.

var arr1 = [1, 2, 3 ];
var arr2 = [4, 5, 6 ];

// Merge arr1 and arr2 into [1, 2, 3, 4, 5, 6]

Here's a summary of how to merge two arrays in JavaScript.

for loop array

This method is the simplest and easiest to implement.

var arr3 = [];

// 遍历arr1
for (var i = 0; i < arr1.length; i++) {
    arr3.push(arr1[i]);
}

// 遍历arr2
for (var j = 0; j < arr2.length; j++) {
    arr3.push(arr2[j]);
}

console.log(arr3); // [1,2,3,4,5,6]

Alternatively, it can be implemented using an enhanced for loop or the forEach() method.

There is almost no problem with the for loop, but many people who pursue streamlined programming will despise this method (hands down).

concat() method

JavaScript's Array object provides a concat() method, which is used to concatenate two or more arrays and return a new array.

var arr3 = arr1.concat(arr2);

console.log(arr3);
// [1,2,3,4,5,6]

It should be noted that the concat() method does not change the original array, but returns a new array. In this way, when we need to merge multiple arrays, it will cause memory waste.

apply() method

The function's apply method has a feature, that is, func.apply(obj, argv), where argv is an array. So we can take advantage of that.

arr1.push.apply(arr1, arr2);

Call the apply() method of the arr1.push function instance, and pass in arr1 and arr2 as parameters, so that the arr1.push method will traverse all the elements of the arr1 and arr2 arrays to achieve the effect of merging.

The simple understanding is that the above code can be regarded as:

arr1.push(4, 5, 6);

This method solves the problem with only one line of code, which can be said to be very 6.

Summarize

There is no difference between the above three methods in routine use, but there are two other minor issues to pay attention to:

1. The above three merging methods have not considered which of the two original arrays has the smaller length in the example. It is a good practice to prejudge which of the two original arrays is larger, and then use the large array to merge the small array, so that you can The number of operations on array elements is reduced, and the execution efficiency of the code is improved.

2. Sometimes we neither want the original array (arr1, arr2) to change, nor do we want to manually add a variable, then we can only use the concat() method.

 

" All the splendor that I have had in my life may eventually need to be repaid with loneliness. "

Reprinted in: https://www.cnblogs.com/yanggb/p/11463434.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324768350&siteId=291194637