How to merge two arrays in JS

In the course of our project, we sometimes encounter situations where we need to merge two arrays into one .

  for example:

1
2
var  a = [1,2,3];
var  b = [4,5,6];

  There are two arrays a and b, and the requirement is to combine the two arrays into one. Methods as below:

  1、concat

    The Array object of js provides a method called concat(), which concatenates two or more arrays and returns the result.

1
var  c = a.concat(b); //c=[1,2,3,4,5,6]

    There is a problem here. After the concat method connects the two arrays a and b, the data of the two arrays a and b will remain unchanged, and a new array will be returned at the same time. In this way, when we need to perform multiple array merging, it will cause a lot of memory waste, so this method is definitely not the best.

  2. For loop

    The general idea is: traverse one of the arrays and add all the elements in the array to the other array in turn. Go directly to the code:

for(var i in b){
    a.push(b[i]);
}

    This way of writing can solve the waste of memory in the first solution, but there will be another problem: ugly! It's not unreasonable to say that, if you can do it with just one line of code, wouldn't it be fun~

  3、apply

    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 this and go directly to the code:

a.push.apply(a,b);

    Call the apply method of the a.push function instance, and pass in b as a parameter, so that the a.push method will traverse all the elements of the b array to achieve the effect of merging.

    It may be a bit confusing here, we can regard b as [4,5,6], which becomes like this:

a.push.apply(a,[4,5,6]);

    Then the above operation is equivalent to:

a.push(4,5,6);

    It's so clear!

  Also, pay attention to two small issues:

  1) The above three merging methods have not considered which of the two arrays a and b has the smaller length.

  So a good practice is to pre-determine which of the two arrays a and b is larger, and then use the large array to merge the small array, which reduces the number of array element operations!

  2) Sometimes we don't want the original array (a, b) to change, so we can only use concat.

Guess you like

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