Home > Net >  I have no idea how to solve this problem, can you help me?
I have no idea how to solve this problem, can you help me?

Time:09-05

I have no idea how to solve this problem, can you help me?

How to transform this :

const array = [["1", ["2", ["3"]]]];

In this (and consider that the array can be an infinite loop) :

<p>
    1
    <p>
        2<p>3</p>
    </p>
</p>;

Not this :

array.forEach(el => {
    el.forEach(el => {
        el.forEach(el =>{

        })
    })
})

CodePudding user response:

NOTE: You can't actually nest <p> elements, so this is with <divs>

(This works even if you have a weird array like ["1", "2", ["3", [["5", "6"]]]])
Use a recursive function:

const array = [["1", ["2", ["3"]]]];

document.body.innerHTML  = createDivs(array)

function createDivs (array) {
  let result = "<div>"
  array.forEach(elem=>{
    if (typeof elem === "string") {
      result  = elem
    } else if (typeof elem === "object") { // Arrays are objects, too
      result  = createDivs(elem)
    }
  })
  result  = "</div>"
  return result
}
div {
  border: 1px solid black;
  padding: 10px;
}

CodePudding user response:

You need to use recursion. Other answers seem to make this unnecessarily complicated. All you need is this:

function makeP(arr) {
    if (arr.length == 1) {
        return "<p>"   arr[0]   "</p>";
    }
    return "<p>"   arr[0]   makeP(arr[1])   "</p>";
}

// Remove the unneeded extra nested array
const array = ["1", ["2", ["3"]]];

console.log(makeP(array));
// output: "<p>1<p>2<p>3</p></p></p>"

If this solved your problem, then you can mark it as correct.

CodePudding user response:

You could check the value and if an array map the values with p tag otherwise take only the value.

const
    format = value => Array.isArray(value)
        ?`<p>${value.map(format).join('')}</p>`
        : value,
    data = ["1", ["2", ["3"]]],
    result = format(data);

console.log(result);

  • Related