metalkat
metalkat

Reputation: 620

javascript recursive string concatentation

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/

Upvotes: 3

Views: 114

Answers (1)

Pranav C Balan
Pranav C Balan

Reputation: 115222

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))

Upvotes: 3

Related Questions