Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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/

like image 297
metalkat Avatar asked Dec 22 '25 20:12

metalkat


1 Answers

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))
like image 122
Pranav C Balan Avatar answered Dec 24 '25 09:12

Pranav C Balan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!