How to turn the following recursive function into a pure function?
<p>The following function appends an object into a nested array (by searching for it recursively):</p>

<pre><code>function appendDeep (arr, obj, newObj) {
  if (arr.indexOf(obj) !== -1) {
    arr.splice(arr.indexOf(obj) + 1, 0, newObj)
  } else {
    arr.map(item =&gt; {
      if (item.children) spliceDeep(item.children, obj)
    })
  }
}
</code></pre>

<p>Example:</p>

<pre><code>const colors = {
  children: [
    {
      name: 'white',
    },
    {
      name: 'yellow',
      children: [
        {
          name: 'black'
        }
      ]
    }
  ]
}

const color = {
  name: 'black'
}

const newColor = {
  name: 'brown'
}

appendDeep(colors.children, color, newColor)
</code></pre>

<p>Result:</p>

<pre><code>children: [
     [
       {
         name: 'white',
       },
       {
         name: 'yellow',
         children: [
           {
             name: 'black'
           },
           {
             name: 'brown'
           }
         ]
       }
     ]
   ]
</code></pre>

<p>As you can see <code>appendDeep</code> returns a side-effect; it modifies <code>arr</code>. So I decided to return the array instead (so the function would become pure):</p>

<pre><code>function findDeep (arr, obj) {
  if (arr.indexOf(obj) !== -1) {
    console.log(arr)
    return arr
  } else {
    arr.map(item =&gt; {
      if (item.children) findDeep(item.children, obj)
    })
  }
}
</code></pre>

<p>And use the new function like this:</p>

<pre><code>const newArr = findDeep(colors.children, color)
newArr.splice(newArr.indexOf(color) + 1, 0, newColor)
</code></pre>

<p>But I get this error:</p>

<pre><code>bundle.js:19893 Uncaught TypeError: Cannot read property 'splice' of undefined
</code></pre>

<p>What I'm a doing wrong?</p>

<p>(Note: Here's the <a href="http://codepen.io/alexcheninfo/pen/ZWopGq" rel="nofollow">CodePen</a>.)</p>

<p>(Note 2: <code>console.log(arr)</code> does return the nested children. But for some reason they become <code>undefined</code> outside of the function.)</p>