Show JavaScript associative array in html table using HTML

Thevagabond

I need to print out the results of a sort on an associative array in JavaScript in a HTML table not using PHP or those things. The sorting works fine as I can see that in the console but it doesn't show the table. Here is the source as far as I have it now:

var array = [{
  name: 'TK345',
  year: 2011,
  custom: 456,
  colour: 'red'
}, {

  name: 'ZJ456',
  year: 2001,
  custom: 96,
  colour: 'black'
}, {
  name: 'AW364',
  year: 1985,
  custom: 001,
  colour: 'cyan'
}, {
  name: 'RT112',
  year: 2012,
  custom: 33,
  colour: 'green'
}, {
  name: 'PO445',
  year: 2012,
  custom: 11,
  colour: 'yellow'
}];

function sortarray(sorter) {

  if (array.length < 1) {
    return -1;
  }

  if (sorter == "name") {

    var byName = array.slice(0);
    var tableout = document.createElement('table');
    var retval = null;
    byName.sort(function(a, b) {

      var x = a.name.toLowerCase();
      var y = b.name.toLowerCase();
      retval = x < y ? -1 : x > y ? 1 : 0;

      tableout.setAttribute('border', '1');
      tableout.setAttribute('width', '100%')
      var row = tableout.insertRow(0);
      for (j = 1; j <= 5; j++) {
        row = tableout.insertRow(j - 1);
        for (i = 1; i <= 4; i++)
          var text = document.createTextNode(retval);
        var cell = row.insertCell(i - 1);
        cell.setAttribute('align', 'center')
        cell.appendChild(text);
      }
    })
    document.getElementById("demo").appendChild(tableout);
    console.log(retval );

  } else if (sorter == "year") {

    var byDate = array.slice(0);
    var tableout = document.createElement('table');
    var retval = null;
    byDate.sort(function(a, b) {

      retval = a.year - b.year;

      tableout.setAttribute('border', '1');
      tableout.setAttribute('width', '100%')
      var row = tableout.insertRow(0);
      for (j = 1; j <= 5; j++) {
        row = tableout.insertRow(j - 1);
        for (i = 1; i <= 4; i++)
          var text = document.createTextNode(retval );
        var cell = row.insertCell(i - 1);
        cell.setAttribute('align', 'center')
        cell.appendChild(text);
      }
    })
    document.getElementById("demo").appendChild(tableout);
    console.log(retval );

  } else {};

};
<!DOCTYPE html>
<html>

<body>
  <button onclick="sortarray('name')">Sort by Name</button>
  <button onclick="sortarray('year')">Sort by Year</button>
  <p id="demo">test</p>
</body>
</html>

So it doesn't show me anything of that table on the page or in the console.

Any ideas?

rpadovani

Your code is broken in so many ways:

  • You have returns in wrong places
  • You do not need two different functions, you just need to have a different sort function
  • Doing something like for (var i = 1; i <= 4; i++) and then use i-1 is bad. Start counting from 0
  • You cannot access to Object using integer, you need to use its keys (see my inner for)
  • You do not need else {}
  • Be careful with indentation, it highlights logic errors as well.
  • You do not need to print the table inside the sort function

I removed some of your errors, this function works:

<!DOCTYPE html>
<html>
<body>
<button onclick="sortarray('name')">Sort by Name</button>
<button onclick="sortarray('year')">Sort by Year</button>
<p id="demo">test</p>

<script>
var array = [   
 {
    name: 'TK345',
    year: 2011,
    custom: 456,
    colour: 'red'
 },
 {

    name: 'ZJ456',
    year: 2001,
    custom: 96,
    colour: 'black'
},
{            
    name: 'AW364',
    year: 1985,
    custom: 001,
    colour: 'cyan'
},    
{
    name: 'RT112',
    year: 2012,
    custom: 33,
    colour: 'green'
},
{
    name: 'PO445',
    year: 2012,
    custom: 11,
    colour: 'yellow'
   }
];

function sortarray(sorter) {
  if (array.length < 1) {return -1;}

  var elems = array.slice(0);
  elems.sort(function(a, b) {
    if (sorter === 'name') {
      var x = a.name.toLowerCase();
      var y = b.name.toLowerCase();
      return x < y ? -1 : x > y ? 1 : 0;
    }

    return a.year - b.year;
  });
  
  var tableout = document.createElement('table');
  tableout.setAttribute('border','1');
  tableout.setAttribute('width','100%');
  
  var row = tableout.insertRow(0);
    
  for (var j=0; j<5; j++) {
    row = tableout.insertRow(j);
    var keys = Object.keys(elems[j]);
    for (var i=0; i < keys.length; i++) {
      var text = document.createTextNode(elems[j][keys[i]]);
      var cell = row.insertCell(i);
      cell.setAttribute('align','center');
      cell.appendChild(text);
    }
  }
  
  document.getElementById("demo").appendChild(tableout);
  console.log(elems);
}

</script>

</body>
</html>

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  3. 3

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  4. 4

    pump.io port in URL

  5. 5

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  8. 8

    Do Idle Snowflake Connections Use Cloud Services Credits?

  9. 9

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

  10. 10

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  11. 11

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  12. 12

    Generate random UUIDv4 with Elm

  13. 13

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  14. 14

    Is it possible to Redo commits removed by GitHub Desktop's Undo on a Mac?

  15. 15

    flutter: dropdown item programmatically unselect problem

  16. 16

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  17. 17

    EXCEL: Find sum of values in one column with criteria from other column

  18. 18

    Pandas - check if dataframe has negative value in any column

  19. 19

    How to use merge windows unallocated space into Ubuntu using GParted?

  20. 20

    Make a B+ Tree concurrent thread safe

  21. 21

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

HotTag

Archive