Handwritten function function: recursive implementation of multi-dimensional array flattening

function design

Function:

Multidimensional array flattening

parameter

Multidimensional Arrays

return value

Flattened array

Ideas

1. A new array ( newArr ) needs to be initialized inside the function as a flattened array container.

2. For non-array type sub-elements, put them directly into newArr

3. For sub-elements of array type, you need to use a recursive method to re-enter the flattening function and re-judge and operate the sub-elements inside the sub-element.

Function implementation

        function flatArr(value){
          let newArr = []
          value.forEach((item,index)=>{
            if(toString.call(item) === '[object Array]'){
                newArr = newArr.concat(flatArr(item))
            }else{
                newArr.push(item)
            }
          })
          return newArr
        }

test

    <script>
        function flatArr(value){
          let newArr = []
          value.forEach((item,index)=>{
            if(toString.call(item) === '[object Array]'){
                newArr = newArr.concat(flatArr(item))
            }else{
                newArr.push(item)
            }
          })
          return newArr
        }
        let Arr = [1,2,3,[4,5,6,[7,8,9]]]
        let newArrs = flatArr(Arr)
        console.log(newArrs,'扁平后的数组')
    </script>

The results are as follows

 

Guess you like

Origin blog.csdn.net/m0_54741495/article/details/132472945