Iterative solution for flattening n-th nested arrays in Javascript

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

提交回复
热议问题