2 of 2
make title describe what code does instead of goals - refer to help center section "Titling your question" on https://codereview.stackexchange.com/help/how-to-ask

clone of HTML tables of data

Need help to refactor this code to look like its done by a pro. Or just put some advice or links to useful stuff.

The idea is to clone a div with two empty tables for two separate arrays of data. div is cloned depending on the longest array length between the two. Then append row of data to them, if rows reach max number the loop continues on another cloned table. loop continues even if the one row is finished appending

<div id="d-page-0">
    <table id="e-tbl-0">
        //content1
        //7 row max
    </table>

    <table id="w-tbl-0">
        //content2
        //21 row max
    </table>
</div>

Javascript part

let d1 = @json($data1); //get data
let d2 = @json($data2); //get data

let ar1 = [];
let ar2 = [];
let s = 0;

for (let i = 7; i < d1.length; i+=7) {
    ar1.push(d1.slice(i, i+7));           //slice data 1
}

for (let i = 21; i < d2.length; i+=21) {
    ar2.push(d2.slice(i, i+21));          //slice data 2
}

ar1.length > ar2.length ? s = ar1.length : s = ar2.length; //take longest array length

for (let v = 0; v < s-1; v++) { //clone div using longest array length
     $("#d-page-0").clone().prop("id", "d-page-"+(v+1)).insertAfter("#d-page-"+v); //clone div, edit id
     $("#d-page-"+(v+1)).find("#e-tbl-0", "table").prop("id", "e-tbl-"+(v+1)); //edit 1st tbl id
     $("#d-page-"+(v+1)).find("#w-tbl-0", "table").prop("id", "w-tbl-"+(v+1)); //edit 2nd tbl id
}

//append 1st data to 1st table
 for (let x = 0; x < ar1.length; x++) {
      let k = ar1[x];
      for (let y = 0; y < k.length; y++) {
           $('#e-tbl-'+x).append(
                `<tr>
                    <td>
                      ar1[x][y].content        
                    </td>
                 </tr>`
            );
      }
}

//append 2nd data to 2nd table
 for (let x = 0; x < ar2.length; x++) {
      let k = ar2[x];
      for (let y = 0; y < k.length; y++) {
           $('#w-tbl-'+x).append(
                `<tr>
                    <td>
                      ar1[x][y].content        
                    </td>
                 </tr>`
            );
      }
}

working sample https://jsfiddle.net/eeneg/pgk3dhac/57/

Son
  • 21
  • 1