Flatten an array with an object

Source: Internet
Author: User

One, flatten an array

A problem encountered a few days ago, there is an array of Var str=[1,2,1,[4,5,[6,7,[8,9]]]; How to say this array is flattened, removing these repeating brackets. I also think for a long time to write out, here to share to you.

  

1 varstr=[1,2,1,[4,5,[6,7,[8,9]]]];2         functionarr (str,depth) {//depth represents the number of flattening3             varNewarr=[]; Create a new array to add the original array elements and the array after the structure4Str.foreach (item=>{5                 if(Array.isarray (item) && depth>0{//array.isarray (); Determines whether an element is an array, the return value is true, or false6Newarr.push (... (Arr (Item,--Depth)))  This takes advantage of the ES6 array of structures and recursion7}Else{8 Newarr.push (item);9                 }Ten             })     One             returnNEWARR; A         } -Console.log (arr (str,8))

Extended:... Use of arrays

1 var arr=[1,5,4,2,10,8,8,20,15,14,12]; 2         function Minarr (arr) {3             return math.min (... arr);//To deconstruct an array 4         }5         console.log (Minarr (arr))//1
Two, the method of flattening an object

I encountered this problem, using a lot of methods, write a lot of code, looked up the data found a very simple method.

1 var obj={0:1,1:1,length:2};

2 Console.log (Array.prototype.slice.call (obj));

Flatten an array with an object

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.