Skip to content Skip to sidebar Skip to footer

Javascript List Loop/recursion To Create An Object

I'm trying to create a function to process a list of numbers relating to depth using recursion or loops in JavaScript. The following 'input' needs to be processed into the 'output

Solution 1:

In fact, it's a very simple problem to solve...

var input   = [0, 1, 2, 3, 1, 2, 0]
  , output  = []
  , parents = [output]
  ;
for(el of input)
  {
  let nv = { number:el, children:[] }
  parents[el].push( nv )
  parents[++el] = nv.children  // save the  @ddress of children:[] for adding items on
  }
console.log( output )
.as-console-wrapper { max-height: 100% !important; top: 0; }

Solution 2:

Here's a functional solution based on recursion and Array.prototype.reduce:

const data = [0, 1, 2, 3, 1, 2, 0]
const last = xs => xs.length > 0 ? xs[xs.length - 1] : undefined
const lastD = (d, t, i = 0) => i > d ? t : lastD(d, last(t).children, i + 1)
const buildIt = xs => xs.reduce(
  (a, x) =>((x === 0 ? a : lastD(x - 1, a)).push({ number: x, children: [] }), a),
  []
)

console.log(buildIt(data))
.as-console-wrapper { max-height: 100% !important; top: 0; }

Note: This solution does not depend on the mutation of additional variables for bookkeeping purposes.

Turns out the actual problem was significantly simpler to solve than my initial misinterpretation!


Post a Comment for "Javascript List Loop/recursion To Create An Object"