Iterative solution for flattening n-th nested arrays in Javascript

后端 未结 8 1090
猫巷女王i
猫巷女王i 2021-02-04 12:46

Can anyone show me an iterative solution for the following problem? I solved it recursively but struggled with an iterative solution. (Facebook Technical Interv

8条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-04 13:41

    Here's a solution that flattens in place.

    function flatten(arr) {
      var i = 0;
    
      if (!Array.isArray(arr)) {
        /* return non-array inputs immediately to avoid errors */
        return arr;
      }
    
      while (i < arr.length) { 
        if (Array.isArray(arr[i])) {
          arr.splice(i, 1, ...arr[i]);
        } else {
          i++;
        }
      }
      return arr;
    }
    

    This solution iterates through the array, flattening each element one level of nesting at a time until it cannot be flattened any more.

提交回复
热议问题