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