title: Why does this recursive flatten array function gives me wrong result? Javascript
body: <p>I'm working on flatten array function. It takes an input like this</p>
  
  <pre><code>const input = [
    {
      "value": "value0",
      "children": []
    },
    {
      "value": "value1",
      "children": [
        {
          "value": "value2",
          "children": [
            {
              "value": "value3",
              "children": []
            }
          ]
        },
        {
          "value": "value4",
          "children": []
        }
      ]
    },
    {
      "value": "value5",
      "children": []
    },
    {
      "value": "value6",
      "children": []
    }
  ];
  </code></pre>
  
  <p>and return an array </p>
  
  <pre><code>[
    {"value":"value0"},
    {"value":"value1"},
    {"value":"value2"},
    {"value":"value3"},
    {"value":"value4"},
    {"value":"value5"},
    {"value":"value6"}
  ]
  </code></pre>
  
  <p>I have solved this problem. Here is my former wrong code and I was trying to debug it</p>
  
  <pre><code>function flatArray(input) {
    if(input.length === 0) return [];
    let res = [];
    input.forEach(i =&gt; {
      for(let key of Object.keys(i)) {
        if(key === 'value') {
          res.push({[key]: i[key]});
        } else {
          const arr = flatArray(i[key]);
          res.concat(arr);
          console.log(res);
        }
      }
    });
    return res;
  }
  </code></pre>
  
  <p>PS: It's wrong because the misuse of <code>concat</code></p>
  
  <p>The output is weird. I got</p>
  
  <p><a href="https://i.stack.imgur.com/WQfEh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WQfEh.png" alt="enter image description here"></a></p>
  
  <p>I'm wondering why the first three are type of object? And why, like the first output, can get an array with 4 elements instead of getting an array with only {value: value0}?</p>
  
  <p>I guess it has something to do with closures but I can't explain this thing. Can anyone help me?</p>