Interview question: An array to insert a fixed position in another array

Source: Internet
Author: User

arr1 = [' A ', ' B ', ' C ']
ARR2 = [' 1 ', ' 2 ', ' 3 ']

Inserts the array arr2 into the array arr1 after the second element B;

Ideas:

Inserting a specific position, we first think of splice, but not directly splice (2, 0, arr2), the result: [' A ', ' B ', [' 1 ', ' 2 ', ' 3 '], ' C '];

So how can we put arr2 elements of a splice into the arr1, there is no simple way?

The answer is yes, another magical function call, apply, (the method that invokes a function is used on another function)

Apply parameters: The first is the function used, the second is an array,

So we're going to turn arr2 into an array for splice (with an array of the first 2 parameters of the splice)

Insert 2 elements in front of arr2: Splice first 2 parameters (start position, delete several elements)

The splice method of array is then pointed to arr1, the most important thing is to pass the newly obtained ARR2 the entire array most parameters to arr1!

This completes the exact location of the ARR2 insert arr1.

var arr1 = [' A ', ' B ', ' C ']; var arr2 = [' 1 ', ' 2 ', ' 3 ']; // Turn the arr2 into an array suitable for splice (contains an array of the first 2 parameters of the splice)Arr2.unshift (2, 0); Array.prototype.splice.apply (arr1, arr2); Console.log (arr1);

------------------------------

If you just insert arr2 at the end of the arr1, you can insert it with push!

var arr1 = [' A ', ' B ', ' C ']; var arr2 = [' 1 ', ' 2 ', ' 3 '];arr1.push.apply (arr1, arr2); Console.log (arr1);

Interview question: An array to insert a fixed position in another array

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.