Iterative solution for flattening n-th nested arrays in Javascript

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

    A fairly concise, readable algorithm:

    function flatten(input) {
      var output = [];
      var todo = [input];
      var current;
    
      while(todo.length) {
        var current = todo.shift();
        if(Array.isArray(current)) {
           todo.unshift.apply(todo, current)
        } else {
          output.push(current);
        }
      }
    
      return output;
    }
    

    This version performs better than my other answer, but is still significantly slower than James Wilkins' answer.

    JSBin

    Tomalak's JSPerf

提交回复
热议问题