Flattening of an intermediate FCC algorithm problem array

Source: Internet
Author: User

Steamroller

The nested array is flattened. You have to consider nesting at different levels.

Array.isarray ()

Ideas:

(1) Traversing arr, if Arr[i] is an array, re-call this function to continue the loop, and then connect with the new array;

(2) If it is not an array, it is added directly into the new array;

Knowledge Points:

(1) The Array . Concat () method is used to combine two or more arrays. Instead of changing an existing array, this method returns a new array;

(2) The Array.push () method adds one or more elements to the end of the array and returns the new length of the array;

(3) Array.isarray () determines whether the passed value is one Array .

Code:

1 functionsteamroller (arr) {2   varNewarr=[];3    for(vari=0;i<arr.length;i++){4     if(Array.isarray (Arr[i])) {5       //if it is an array, re-call this function to continue the loop, and then connect to the new array6Newarr=Newarr.concat (Steamroller (arr[i));7}Else{8      //if it is not an array, add it directly into the new array9 Newarr.push (Arr[i]);Ten     } One   } A   returnNEWARR; - } -Steamroller ([1, [2,222,[22,[2,[2]]], [3, [[4]]]);

Flattening of an intermediate FCC algorithm problem array

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.