DEV Community

Discussion on: Daily Challenge #226 - Array to HTML Table

Collapse
 
georgewl profile image
George WL

Es6+ JavaScript

function toTable(datalist, isFirstRowHeader=false, isIndexed=false){
  let headers=[]
  if(isFirstRowHeader&&datalist&&datalist[0].length>0){
    // parse first row
      headers = datalist[0]
      if (isIndexed&& headers&& headers.length>1){
        headers.unshift('')
      }
    }
  const headerRowHTML = toHtmlHead(headers)
  const bodyHTML = toHtmlBody(datalist.slice(isFirstRowHeader?1:0),isIndexed);
  return `<table>${headerRowHTML}${bodyHTML}</table>`
}
const toHtmlHead = headers =>{
    return `<thead><tr>${
      headers.map(header=>`<th>${
        header
      }</th>`).join('')
    }</tr></thead>`
}
const toHtmlBody = (bodyData,isIndexed)=>{
  return `<tbody>${bodyData.length>1?
    bodyData.map((row,index)=>`<tr>${
      isIndexed ?
        `<td>${index+1}</td>`:
          ''
          }${
      row
        .map(cell=>`<td>${cell}</td>`)
        .join('')}</tr>`)
        .join('')
    :
      bodyData
      }` 
}

I think that's all a bit messy though and I could do it even simpler... Just would need some more thought to it.