Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Calculadora

0

66
Vistas
Split one big table into multiple tables based on content of acolumn in each row

I looked at previous similar questions and only found one answer with the following code splitting the data into 2 tables:

    // ==UserScript==
// @name        TABLE SPLITTER
// @namespace   http://www.w3schools.com/
// @description DESCRIPTION!!!
// @include     http://www.w3schools.com/css/css_table.asp
// @require     http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
// @require     https://raw.github.com/tomgrohl/jQuery-plugins/master/jcookie/script/jquery.jcookie.min.js
// @version     1
// ==/UserScript==
$(function(){
        // YOUR JAVASCRIPT CODE HERE
        // YOU HAVE JQUERY INCLUDED
    setTimeout(function(){
        var mainTable = $("table");
        var splitBy = 3;
        var rows = mainTable.find ( "tr" ).slice( splitBy );
        var secondTable = $("<table id='secondTable' style='background:pink;'><tbody></tbody></table>").insertAfter("table");
        secondTable.find("tbody").append(rows);
        console.log(secondTable);
        mainTable.find ( "tr" ).slice( splitBy ).remove();

    }, 3000);
});

I am looking for something like this that will split the information to tables base on the amount of different options i have.

ultimately i would like something like: Goal

Or even better remove the type from the output and have it show before each of the new tables like this: option 2

Not sure if that even possible and would love some help.

7 months ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

This is not the optimal solution, you can get the idea and improve it.

Read JS comments.

var dynamicData = $('#dynamicData'); // To identify the parent that we will append data to.

$(document).ready(function(){

  $('.types').each(function(){ // loop on each type and check if that type not appended inside '#dynamicData' as 'h5', if no,t append it and append a table related to it
    var name = $.trim($(this).text());
    var check = $('h5#i_' + name , dynamicData).length;
    if (check === 0){
      $(dynamicData).append('<h5 id="i_' + name + '">' + name + '</h5>');      
      $(dynamicData).append('<table id="t_' + name + '" class="table table-hover table-striped table-bordered"></table>');
      $('table#t_' + name).append('<thead>'+
        '<tr>'+
        '<th>Product</th>'+
        '<th>Price</th>'+
        '</tr>'+
        '</thead>'+
        '<tbody>'+
      '</tbody>');
    }
  });
  
  $('#allContent > tr').each(function(){ // loop on each row in '#allContent' and read '.types' class, then clone this row and remove the type then append it inside the target table using id
    var name = $.trim($('.types',this).text());
    $(this).clone().find('.types').remove().end().appendTo('table#t_' + name + ' > tbody');
  });
  
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">


<h4 class="text-center text-danger">Before:</h4>
<table class="table table-hover table-striped table-bordered">
  <thead>  
    <tr>
      <th>Product</th>
      <th>Price</th>
      <th>Type</th>
    </tr>
  </thead>
  <tbody id="allContent">
    <tr>
      <td>TV</td>
      <td>250$</td>
      <td class="types">Product</td>
    </tr>
    <tr>
      <td>Channel</td>
      <td>1$</td>
      <td class="types">Service</td>
    </tr>
    <tr>
      <td>Channel</td>
      <td>1$</td>
      <td class="types">Service</td>
    </tr>
    <tr>
      <td>DVD</td>
      <td>14$</td>
      <td class="types">Product</td>
    </tr>
    <tr>
      <td>Support</td>
      <td>15$</td>
      <td class="types">Team</td>
    </tr>
  </tbody>
</table>

<h4 class="text-center text-danger">After:</h4>
<div id="dynamicData"></div>

7 months ago · Juan Pablo Isaza Denunciar

0

My first thought is make a unique list of the types. Then loop over that list, cloning the original table for each. Then loop through the cloned table and remove everything that you don't want there. Definitely not the most efficient, but it's simple and it works.

let types = [... new Set($('table.original tr td:last-of-type')
              .get().map(type => type.textContent))];

//create a container for the cloned tables
$('table.original').after(`<h4>After:</h4><div class="cloned-tables"></div>`)

//loop over types, clone tables, modify accordingly
$.each(types, function(index, type) {
  $(`<p class="type">${type}</p>${$('table.original')[0].outerHTML}`)
    .appendTo('.cloned-tables')
    .find('tr td:last-of-type').each(function() {
      if (this.textContent !== type) { this.parentElement.remove();  }        
      this.remove();
  });
});

//remove all type header cells
$(`.cloned-tables table th:last-of-type`).remove();
h4{color: red;}
.type{color: blue;}
<h4>Before:</h4>
<table class="original">
  <thead>  
    <tr>
      <th>Product</th>
      <th>Price</th>
      <th>Type</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>TV</td>
      <td>$250</td>
      <td>Product</td>
    </tr>
    <tr>
      <td>Channel</td>
      <td>$1</td>
      <td>Service</td>
    </tr>
    <tr>
      <td>Channel</td>
      <td>$1</td>
      <td>Service</td>
    </tr>
    <tr>
      <td>DVD</td>
      <td>$14</td>
      <td>Product</td>
    </tr>
    <tr>
      <td>Support</td>
      <td>$15</td>
      <td>Team</td>
    </tr>
  </tbody>
</table>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Another thought on using greasemonkey, make sure that the table exist and is populated before you try and do anything with it. Greasemonkey is in a different scope than the original code, so document.ready() is inaccurate. Sometimes things load very asychronously, which will make valid code seem broken. I tend to do something like this:

let loading = setInterval(function() {
  if ($('table.original').length) {
    clearInterval(loading);
    //greasmonkey code here
  }
}, 1000);
7 months ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar empleo Planes Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2023 PeakU Inc. All Rights Reserved.