title: Create nested array in Javascript
body: <p>I'm trying to convert my data from API to my needs. Would like to create a nested array from plain array. I would like to group elements by <code>parentId</code> property, if <code>parentId</code> would not exist I would put it as a root. <code>id</code> value is unique. Like so (raw data):</p>
  
  <pre><code>[
      {id: 1, name: 'sensor'},
      {id: 2, name: 'sensor', parent: 1},
      {id: 3, name: 'sensor', parent: 1},
      {id: 4, name: 'sensor', parent: 3},
      {id: 5, name: 'sensor'},
      {id: 6, name: 'sensor', parent: 5}
  ]
  </code></pre>
  
  <p>Converted Data: </p>
  
  <pre><code>  const results = [
      {
        id: 1,
        name: "sensor",
        children: [
          { id: 2, name: "sensor", parent: 1 },
          {
            id: 3,
            name: "sensor",
            parent: 1,
            children: [{ id: 4, name: "sensor", parent: 3 }]
          }
        ]
      },
      { id: 5, name: "sensor", children: [{ id: 6, name: "sensor", parent: 5 }] }
    ];
  </code></pre>
  
  <p>I found this recursive method but it assumes that the parent property exist for every element in an array. In my example root level element would not have parent property. </p>
  
  <pre><code>function getNestedChildren(arr, parent) {
      var out = []
      for(var i in arr) {
          if(arr[i].parent == parent) {
              var children = getNestedChildren(arr, arr[i].id)
  
              if(children.length) {
                  arr[i].children = children
              }
              out.push(arr[i])
          }
      }
      return out
  }
  </code></pre>