This is the second day of my participation in the August More Text Challenge

The concept of array flattening is to convert a multidimensional array into a one-dimensional array

[1, [2, 3, [4, 5]] ------> [1, 2, 3, 4, 5]Copy the code

1. Recursive implementation

The way we loop recursively, we go through one item at a time, and if each item is still an array we’re going to recurse recursively. Our recursive subproblem is to return an array per layer.

If we decide that the current is an array, then the recursion must return an array, we just need to concatenate our previous newarr with our own.

Code implementation:

   let arr = [1, [2, [3, 4, 5]]];
 ​
   function flatten(arr) {
     let newarr = [];
     let length = arr.length;
     for (let i = 0; i < length; i++) {
       if (Array.isArray(arr[i])) {
         newarr = newarr.concat(flatten(arr[i]))
       } else {
         newarr.push(arr[i])
       }
     }
     return newarr
   }
   console.log(flatten(arr))
Copy the code

2. Reduce function iteration

This method is not much different from the above method, which uses a loop to process the array. Here, we can use reduce to realize array splicing, thus simplifying the first method.

function flatten(arr) { return arr.reduce((pre, next) => { return pre.concat(Array.isArray(next)? flatten(next):[next]) }, []) }Copy the code

3. Extend operator implementation

This implementation is that we expand the operator can get us each element of the array, in this case we can use it with concat to merge, that’s not enough, we also need to point, whether in our current arr array elements if so continue to use the extended operator to merge.

The implementation is as follows:

function flatten(arr) { while(arr.some((item)=>Array.isArray(item))){ arr=[].concat(... arr) } return arr } console.log(flatten(arr))Copy the code

4. Splite and toString

The split and toString methods work together to flatout arrays. Since arrays carry a toString method by default, we can convert arrays directly to comma-separated strings, and then use split to convert strings back to arrays, as shown in the following code:

  function flatten(arr) {
    return arr.toString().split(',')
   }
   console.log(flatten(arr))
Copy the code

5. Flat in ES6

We can also flat the array directly by calling the flat method in ES6. Arr. Flat ([depth])

Depth is the parameter flat. Depth is the expansion depth of the array that can be passed (the default is left blank and the value is 1). If the number of layers is uncertain, the parameter can be passed into Infinity, indicating that no matter how many layers are expanded:

   function flatten(arr) {
     return arr.flat(Infinity)
   }
   console.log(flatten(arr))
Copy the code

\