There is a script:

var quene = [5, 4, 3, 1, 1, 2]; var cur_par = [5, 5, 5, 4, 3, 3]; var current_parrent, path = [], parent_path = []; while (quene != '') { cur_top = quene.shift(); current_parrent = cur_par.shift(); if (path == '') { path[path.length] = [cur_top]; parent_path[cur_top] = [path.length - 1]; } else { path.push(path[parent_path[current_parrent]]); //этот push добавляет строки копируя определенную предыдущую строку this_top = cur_top; path[path.length - 1].push(this_top); //этот добавляет значения в строки parent_path[cur_top] = [path.length - 1]; } } console.log(path); 

Output console.log(path); must be necessarily numeric and as follows:

 [[5], [5, 4], [5, 3], [5, 4, 1], [5, 3, 1], [5, 3, 2]] 

How do I get here 6 arrays of 6 elements, just by mixing all the points together?

 [Array[6], Array[6], Array[6], Array[6], Array[6], Array[6]] 

Comments explain my line of thought.

    1 answer 1

    The main problem is that the link to the same array is kept, so when adding elements to it, the changes were visible everywhere.

    For correction, you can use the methods concat or slice

    In addition, to check the presence of elements in the array is better to use the length property.

     var quene = [5, 4, 3, 1, 1, 2]; var cur_par = [5, 5, 5, 4, 3, 3]; var current_parrent, path = [], parent_path = []; while (quene.length > 0) { cur_top = quene.shift(); current_parrent = cur_par.shift(); if (path.length == 0) { path[path.length] = [cur_top]; parent_path[cur_top] = [path.length - 1]; } else { path.push([].concat(path[parent_path[current_parrent]])); //этот push добавляет строки копируя определенную предыдущую строку this_top = cur_top; path[path.length - 1].push(this_top); //этот добавляет значения в строки parent_path[cur_top] = [path.length - 1]; } } console.log(JSON.stringify(path)); 

    • You are a genius. But I can not understand. How exactly did I keep there a link to the same element? - Telion
    • one
      @Levelleor, arrays are stored in your path . in the line path.push([].concat(path[parent_path[current_parrent]])) you get a link to the array path[parent_path[current_parrent]]) and save it in the path as a result you have many links and one array - Grundy