Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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", and it needs to work for arbitary lists.

One thing to note is that numbers increase by either 0 or 1 but may decrease by any amount.

var input = [0, 1, 2, 3, 1, 2, 0]

var output =
  [ { number: 0, children: 
      [ { number: 1, children: 
          [ { number: 2, children: 
              [ { number: 3, children: [] } ]
            } 
          ] 
        } 
      , { number: 1, children: 
          [ { number: 2, children: [] } ]
        } 
      ] 
    } 
  , { number: 0, children: [] } 
  ] 

I worked it out myself, although it needs some refinement.

var example = [0, 1, 2, 2, 3, 1, 2, 0]
var tokens = []
var last = 0
const createJSON = (input, output) => {
  if (input[0] === last) {
    output.push({ num: input[0], children: [] })
    createJSON(input.splice(1), output)
  } 
  else if (input[0] > last) {
    last = input[0]
    output.push(createJSON(input, output[output.length-1].children))
  } 
  else if (input[0] < last) {
    var steps = input[0]
    var tmp = tokens
    while (steps > 0) {
      tmp = tmp[tmp.length-1].children
      steps--
    }
    tmp.push({ num: input[0], children: [] })
    createJSON(input.splice(1), tmp)
  }
}
createJSON(example, tokens)
console.log(tokens)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
166 views
Welcome To Ask or Share your Answers For Others

1 Answer

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; }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...