Home > OS >  Function which take array and return nested list
Function which take array and return nested list

Time:09-03

    const generateList = array => {
        const newList = document.createElement("ul");
        document.body.appendChild(newList);
        for(let i = 0; i < array.length; i  = 1) {
            if(!Array.isArray(array[i])) {
                const newItem = document.createElement("li");
                newList.appendChild(newItem);
                newItem.innerHTML = array[i];
            } else if (Array.isArray(array[i])) {
                const get = array[i];
                const nestedList = document.createElement("li");
                document.querySelector("ul").appendChild(nestedList);
                const newUl = document.createElement("ul");
                document.querySelector("li").appendChild(newUl);
                const nestedItem = document.createElement("ul");
                nestedList.appendChild(nestedItem);
                    for (let j = 0; j < get.length; j  = 1) {
                        const nestedItemX = document.createElement("li");
                        nestedItem.appendChild(nestedItemX);
                        nestedItemX.innerHTML = get[j];
                    }
            }
        }
    }

    generateList([[0],1,2,[1.1,1.2,1.3],3,["One","Two","Three"]]);

Hello, I have task, make function which take array(for example[1,2,3[3.1,3.2],4]) and make list in HTML like this ul > li > 1 but if nested array its create new empty list. Must be like this, from start like this ul > li > ul > li enter image description here

I wrote some code but its make inside li empty and I cannot understand why. Please correct me and explain why its happen? Structure should be like on picture bellow

CodePudding user response:

I see now, you were indeed creating some unneccesary ULs (only visible when inspecting sourcecode). I cleaned it up:

const generateList = array => {
  const newList = document.createElement("ul");
  for (let i = 0; i < array.length; i  = 1){
    const newItem = document.createElement("li");
    if (!Array.isArray(array[i])){
      newItem.innerHTML = array[i];
    }
    else{
      const nestedArray = array[i];
      const nestedList = document.createElement("ul");
      for (let j = 0; j < nestedArray.length; j  = 1){
        const nestedItem = document.createElement("li");
        nestedItem.innerHTML = nestedArray[j];
        nestedList.appendChild(nestedItem);
      }
      newItem.appendChild(nestedList);
    }
    newList.appendChild(newItem);
  }
  document.body.appendChild(newList);
}

generateList([[0],1,2,[1.1,1.2,1.3],3,["One","Two","Three"]]);
  • Related