Iterative solution for flattening n-th nested arrays in Javascript

后端 未结 8 1088
猫巷女王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:43

    A different iterative algorithm:

    function flatten2(input) {
      var output = [];
      var todo = [input];
      var current;
      var head;
    
      while(todo.length) {
        var current = todo.shift();
        if(Array.isArray(current)) {
          current = current.slice();
          head = current.shift();
          if(current.length) {
            todo.unshift(current)
          }
    
          todo.unshift(head);
        } else {
          output.push(current);
        }
      }
    
      return output;
    }
    
    • Put all elements on a stack.
    • While the stack is not empty, remove the first element.
      • If that element is a scalar, add it to the output.
      • If that element is an array, split it into head (first element) and tail (remaining elements) and add both to the stack.

    As Tomalak's JSPerf shows, this is pretty slow.

    JSBin

    0 讨论(0)
  • 2021-02-04 13:48
    function flatten(array){
      for(var i=0;i<array.length;i++)
        if(Array.isArray(array[i]))
          array.splice.apply(array,[i,1].concat(array[i--]));
      return array;
    }
    

    This in-place solution is faster than Lupe's, now that I've removed all of the inner curly brackets (I inlined the i-- in the concat parameter to do that).

    0 讨论(0)
提交回复
热议问题