JSFiddle - React, Tailwind, and code Playground

by Prathameshsb

HTML

<div id='tableContainer'>

</div>

JavaScript

// Function to create the table
const createDeviceTable = (devices) => {
  // Parse and sort the devices alphabetically
  const sortedDevices = devices.map(device => {
    const [deviceName, datacenter] = device.split('.');
    const [deviceType] = deviceName.split('');
    return { deviceName, deviceType, datacenter };
  }).sort((a, b) => {
    if (a.deviceName < b.deviceName) return -1;
    if (a.deviceName > b.deviceName) return 1;
    return 0;
  });

  // Generate HTML for the table
  const table = document.createElement('table');
  const tableHeader = table.createTHead();
  const row = tableHeader.insertRow();

  // Create table headers
  ['Device Name', 'Device Type', 'Datacenter'].forEach(headerText => {
    const th = document.createElement('th');
    const text = document.createTextNode(headerText);
    th.appendChild(text);
    row.appendChild(th);
  });

  // Create table rows with sorted device information
  sortedDevices.forEach(device => {
    const newRow = table.insertRow();
    Object.values(device).forEach(value => {
      const cell = newRow.insertCell();
      const text = document.createTextNode(value);
      cell.appendChild(text);
    });
  });

  // Apply CSS for table styling
  table.style.borderCollapse = 'collapse';
  // Add more CSS styles as needed

  return table;
};

// Example to run the code
const devices = [
  'ssw001.atn1', 'ssw002.atn1', 'ssw003.atn1', 'ssw012.prn1',
  'ssw004.atn1', 'ssw085.atn1', 'ssw006.prn1', 'ssw007.prn1',
  'ssw008.lla2', 'ssw009.lla2', 'esw001.atn1', 'ssw010.lla2',
  'ssw011.lla2', 'esw002.atn1', 'esw003.atn1', 'esw004.atn1',
  'esw885.atn1', 'esw006.atn1', 'esw007.lla2', 'esw008.lla2',
  'fsw001.atn1', 'fsw002.atn1', 'fsw003.atn1', 'fsw004.atn1',
  'fsw005.atn1', 'fsw006.lla2', 'fsw007.lla2', 'fsw008.lla2'
];

// Render the table to a HTML element with id 'tableContainer'
const tableContainer = document.getElementById('tableContainer');
if (tableContainer) {
  const table = createDeviceTable(devices);
...