Adding an array into an HTML table with JavaScript

I need help with inserting an array into a table format. My code snippet should display the data in this structure:

Student Name Student Mark Student Grade

If anyone has insight on how to achieve this, I would really appreciate it.

let gradeAwarded;
let maxVal;
let A =0;
let B =0;
let C=0;
let F=0;
let sum = 0
let average
let repeat, studentArr = [], markArr = [];

while (repeat !== 'n'){
    studentArr.push(prompt("Enter Student Name: ", "Ross"));
    markArr.push(parseInt (prompt("Enter Student mark: ", 50)));

    if (markArr < 0 || markArr > 100){
        alert("Grade out of bounds");
    }else if (markArr >= 83){
        gradeAwarded = "A";
        A = A + 1;
    }else if (markArr >= 70){
        gradeAwarded = "B";
        B = B + 1;
    }else if (markArr >= 50){
        gradeAwarded = "C";
        C = C + 1;    
    }else if (markArr >= 0){
        gradeAwarded = "F";
        F = F + 1;                                                        
    }
     repeat = prompt ("Do you want to enter another student: y/n");

}  

Array.prototype.maxValue = function() {
  return Math.max.apply(Math, markArr);
};

Array.prototype.minValue = function() {
  return Math.min.apply(Math, markArr);
};
for(let x = 0; x < markArr.length; x ++)
{
  sum = sum + markArr[x]; 
}

average = sum / markArr.length; 
let minValue = markArr.minValue();
let maxValue = markArr.maxValue();

for(let i = 0; i < markArr.length; i++)
document.write(<tr> markArr[i] </tr>);
    document.write("The Highest mark was : "+maxValue+"<br>");
    document.write("The Lowest mark was : "+minValue +"<br>");
    document.write("The Average mark was : "+average+"<br>");
    document.write("number A grades : "+A+"<br>");
    document.write("number B grades : "+B+"<br>");
    document.write("number C grades : "+C+"<br>");
    document.write("number F grades : "+F+"<br>");

Answer №1

Here is a helpful solution:

            var markAwarded;
            var gradeAwarded;
            var max;
            var A = 0;
            var B = 0;
          var D = 0;
            var E = 0;
            var totalMarks = 0
            var averageMarks
            var repeat, studentArr = [], markArr = [], gradeArr = [];
            while (repeat !== 'n') {
                studentArr.push(prompt("Enter Student Name: ", "Ross"));
                markAwarded = parseInt(prompt("Enter Student mark: ", 50));
                markArr.push(markAwarded);

                if (markAwarded < 0 || markAwarded > 100) {
                    alert("Grade out of bounds");
                } else if (markAwarded >= 83) {
                    gradeAwarded = "A";
                    A = A + 1;
                } else if (markAwarded >= 70) {
                    gradeAwarded = "B";
                    B = B + 1;
                } else if (markAwarded >= 50) {
                    gradeAwarded = "C";
                    C = C + 1;
                } else if (markAwarded >= 0) {
                    gradeAwarded = "F";
                    F = F + 1;
                }
                gradeArr.push(gradeAwarded);
                repeat = prompt("Do you want to enter another student: y/n");

            }

            Array.prototype.maximize = function () {
                return Math.max.apply(Math, markArr);
            };

            Array.prototype.minimize = function () {
                return Math.min.apply(Math, markArr);
            };
            for (var x = 0; x < markArr.length; x++) {
                totalMarks = totalMarks + markArr[x];
            }

            averageMarks = totalMarks / markArr.length;
            var minimumMark = markArr.minimize();
            var maximumMark = markArr.maximize();

            document.write("<table style='border:1px solid black;'><tr><th>Student Name</th><th>Student Mark</th><th>Student Grade </th></tr>");
            for (var i = 0; i < markArr.length; i++) {
                document.write("<tr><td>" + studentArr[i] + "</td><td>" + markArr[i] + "</td><td>" + gradeArr[i] + "</td> </tr>");
            }
            document.write("</table>");
            document.write("The Highest mark was : " + maximumMark + "<br>");
            document.write("The Lowest mark was : " + minimumMark + "<br>");
            document.write("The Average mark was : " + averageMarks + "<br>");
            document.write("number A grades : " + A + "<br>");
            document.write("number B grades : " + B + "<br>");
            document.write("number C grades : " + C + "<br>");
            document.write("number F grades : " + F + "<br>");

Answer №2

For those looking to generate a table solely using javascript, you can use functions similar to the following:

var bodyElement = document.getElementsByTagName('body')[0];
var tableElement = document.createElement('table');
var rowElement = document.createElement('tr');
var cellElement = document.createElement('td');
cellElement.nodeValue = dataToBeDisplayedInCell;

rowElement.appendChild(cellElement);
tableElement.appendChild(rowElement);
bodyElement.appendChild(tableElement);

Answer №3

Have you checked out this resource: Learn how to display a JavaScript array in a table

There are numerous methods for converting an array into a table.

Answer №4

Give this code a shot

  <script>
  var gradeAwarded;
  var max;
  var A =0;
  var B =0;
  var C=0;
  var F=0;
  var Sum = 0
  var average
  var repeat, studentArr = [], markArr = [];

  while (repeat !== 'n'){
      studentArr.push(prompt("Please input Student Name: ", "Ross"));
      markArr.push(parseInt (prompt("Please input Student mark: ", 50)));

      if (markArr <0 || markArr >100){
          alert("Grade is out of bounds");
      }else if (markArr >= 83){
          gradeAwarded = "A";
          A = A + 1;
      }else if (markArr >= 70){
          gradeAwarded = "B";
          B = B+1;
      }else if (markArr >= 50){
          gradeAwarded = "C";
          C = C+1;    
      }else if (markArr >= 0){
          gradeAwarded = "F";
          F = F+1;                                                        
      }
       repeat = prompt ("Do you want to enter another student: y/n");

  }  

  Array.prototype.max = function() {
    return Math.max.apply(Math, markArr);
  };

  Array.prototype.min = function() {
    return Math.min.apply(Math, markArr);
  };
  for(var x = 0; x < markArr.length; x ++)
  {
    Sum = Sum + markArr[x]; 
  }

  average = Sum / markArr.length; 
  var min = markArr.min();
  var max = markArr.max();
  document.write("<table>");
  for(var i = 0; i < markArr.length; i++){
    document.write("<tr>");
    document.write("<td>"+  studentArr[i] + '</td>');
    document.write("<td>"+  markArr[i] + '</td>');
    if (markArr[i] >= 83){
          gradeAwarded = "A";
      }else if (markArr[i] >= 70){
          gradeAwarded = "B";
      }else if (markArr[i] >= 50){
          gradeAwarded = "C";
      }else if (markArr[i] >= 0){
          gradeAwarded = "F";
      }
      document.write("<td>"+  gradeAwarded + '</td>');
    }
      document.write("</table>");
      document.write("The Highest mark achieved : "+max+"<br>");
      document.write("The Lowest mark achieved : "+min +"<br>");
      document.write("The Average mark achieved : "+average+"<br>");
      document.write("Number of A grades : "+A+"<br>");
      document.write("Number of B grades : "+B+"<br>");
      document.write("Number of C grades : "+C+"<br>");
      document.write("Number of F grades : "+F+"<br>");

  </script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to iterate over the request body in Node.js using Express?

When I send a request with data in the form of an array of objects: [ {id: "1"}, {id: "2"}, {id: "3"} ] I am utilizing JSON.stringify() and my req.body ends up looking like this: { '{"id":"1"} ...

Transferring a PHP array to JavaScript using AJAX

I have spent time searching for answers to my issue with no success. My PHP file includes the following array: $data = ['logged' => $_SESSION['loggedin'], 'sessName' => $_SESSION['name']]; echo json_encode($dat ...

Updating Tailwind CSS to accommodate older web browsers by converting modern rgba() notation to be browser-compatible

I am facing a challenge with Tailwind CSS v3+ as it builds colors into the rgb space/color notation that is not compatible with an older browser (Safari 11) that my web app now needs to support. For example, rgb(163 160 158 / var(--tw-bg-opacity) The iss ...

How do you properly bind multiple events in jQuery and then unbind just a few of them?

Is it possible to bind multiple events, then unbind a couple of them? This is what I'm trying to achieve: When hovering over the element, the background color changes and changes back when hovering out. But when clicking the element, I want to disabl ...

Routing WebSocket connections with Node.js

Currently, I am in the process of developing a chat application for my company which will run on node js with websocket (ws). The app is designed to cater to various departments within the organization, each with its own set of users. My goal is to ensure ...

Error: The array geocode-api encountered an IndexOutOfRangeException, indicating that the specified index was beyond the allowable bounds

I encountered an "index was outside the bounds of the array" exception while trying to retrieve the latitude value from a geocode request on this line of code: string strLat = myCoordenates.Results[0].Geometry.Location.Lat.ToString(); The purpose of this ...

changing the elements' classes by using a carousel

Having trouble with a custom carousel and unable to use the standard Bootstrap carousel. This is how my code is structured: Images: <img src="1.img"/> <img src="2.img"/> <img src="3.img"/> Prev / Next buttons: <div class="left ...

Exploring ways to utilize functions and operators with the output of custom VueJS filters?

I have implemented a Vue filter called timeconverter to alter the date format of a string. My goal is to verify if the outcome of {{ time | timeconverter }} is before the present time. Is there a way to utilize JavaScript functions on the output generated ...

Attempting to assign a new class to a <div> using JavaScript

I'm facing an issue where I need to add a class to a div without replacing the existing classes. Despite my code being correct, it doesn't seem to work as expected. function clickTab(clicked_id) { var x = clicked_id x.className += " active ...

Navigate through an overflowing element in react/next

I have a component with a fixed width and overflow-x-auto. I want to hide the scroll bar and replace it with arrow buttons for scrolling left and right. How can I add this functionality to my component? Here is the code for my component: <div className ...

What method can I use in Javascript to extract the mealtype data from the Edamam nutritional API?

My goal is to extract the mealtype information from the API linked below. After reviewing the API, it seems that a POST request is required to retrieve mealType data. However, I am uncertain about the correct syntax for this request. For instance, if a u ...

Google Maps displays grayscale overlays on the latest version update

Hello, I am facing a challenging issue with the Google Maps API. I have come across some similar threads discussing this problem, but unfortunately, they did not provide a solution that suits my specific case. Currently, I am working on an angular.js 1. ...

Using JavaScript to call an API in PHP and determine how to handle a response that is not equal to 200 by printing an

Greetings! I am aiming for a scenario where, upon clicking the link, the user's parameter is transferred to JavaScript. This parameter will then be used in ajax to trigger a call to my PHP file containing the API. The API, after processing the parame ...

Retrieving a specific item from a sql-array using jOOQ

How do I retrieve an item from an array in JOOQ similar to this SQL query? SELECT (ARRAY_AGG(id))[1] FROM entities; Is there a way to achieve this using JOOQ? dsl().select(arrayAgg(ENTITIES.ID).get(1)).from(ENTITIES).fetch(); Alternatively, can I acces ...

Is it secure to use ES6 in Typescript with nodejs/koa?

As I transition to using TypeScript in a Node.js/koa project, I came across the need to modify the .tsconfig file to target ES6. Otherwise, an error message will appear stating: Generators are only available when targeting ECMAScript 6 or higher. // index ...

Speed up width calculations in jQuery/JavaScript with these efficient techniques

I am facing a challenge with a table that has 100 columns. I'm currently iterating through all the th elements in a loop to manually specify the width of each th. var $ths = $("table th"); $ths.each(function (i, th) { var $th = $(th); var wid ...

Instructions on creating an input field and a slider simultaneously

Currently, I am exploring the world of CSS 3D transforms and I am particularly interested in creating sliders to manage these transforms. I recently stumbled upon the Three.js editor and was impressed by how it handles the positioning, rotation, and scalin ...

JavaScript - The onkeypress event continuously adds text to the end

In my Angular application, I have implemented an input field with the onkeypress event handler to automatically remove any commas entered by the user: <input name="option" ng-model="main.optionToAdd" onkeypress="this.value = this.value.replace(/,/g ...

Creating nested objects in JavaScript can be achieved by using the reduce method to return objects in an array

Looking to nest each element of an array into a new object within another object let newArr = ['Parent', 'Child'] Desiring the array to be transformed into this structure Parent[Child]={} Seeking a way to iterate through the array a ...

Retrieve specific information from checkboxes within a form

I'm working on a form that includes multiple checkboxes populated with data from a JSON file using ng-repeat. After submitting the form, I need to retrieve the data from the checked checkboxes. How can I accomplish this in my controller after the form ...