3

I am trying to recursively turn a nested array into an ordered HTML list. My test array looks like: [['A','B','C'],['D',['E','F','G']]] And the result should look like:

    1. A
    2. B
    3. C
    1. D
      1. E
      2. F
      3. G

But it is currently returning:

    1. A
    2. B
    3. C
    1. D
    2. E,F,G

When I print it out, the recursion is successful, but gets overwritten by the previous step. I feel like it has to do with declaring the string at the top of the function, but I am not sure how else to approach it.

JSFIDDLE: https://jsfiddle.net/nzyjoawc/2/

3
  • 1
    Show your code? Commented Nov 21, 2016 at 3:39
  • I added a JSFiddle at the top but I can post it here as well. Commented Nov 21, 2016 at 3:42
  • Maybe just make it stand out more, seems people are missing it. Commented Nov 21, 2016 at 3:43

1 Answer 1

3

Do it with recursion and use Array#forEach method for iterating over array.

var a = [
  ['A', 'B', 'C'],
  ['D', ['E', 'F', 'G']]
];

function gen(arr) {
  // create `ol` eleemnt
  var ol = document.createElement('ol');
  // iterate over the array eleemnt
  arr.forEach(function(v) {
    // create list item `li`
    var li = document.createElement('li');
    // if array element is an array then do recursion 
    // and append the returnd value
    if (Array.isArray(v))
      li.appendChild(gen(v));
    // else set the content as array value
    else
      li.innerHTML = v;
    // append the list item to the list
    ol.appendChild(li);
  });
  // resturn the genarated list
  return ol;
}

document.body.appendChild(gen(a))

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.