Finding the percentage within Multi-Dimensional Arrays

In my Javascript Multi-Dimensional Arrays, it contains 3 values: NAME, ROUND, Number of Votes

Sample data:

NAME| ROUND| Number of Votes

Evan | 1 | 2

John | 1 | 1

Mary | 1 | 3

Evan | 2 | 4

John | 2 | 1

I aim to showcase the Voting results on screen with percentages (based on ROUND), just like this:

ROUND 1

Evan - 2 Votes (33.3%)

John - 1 Vote (16.7%)

Mary - 3 Votes (50%)

ROUND 2

Evan - 4 Votes (80%)

John - 1 Vote (20%)

Thanks, Joe

Below is my javascript code:.

function rpt_result(){
var temp = '';
var l_temp = '';
var html = '';
var num = obj('remain').value;
var total = 0;
var tmp_round = 0;
html += '<html>';
html += '<head><title>Voting Result</title>';
html += '</head>';
html += '<body>';
html += '<table width="760" align="center"><tr><td align="center"><h2>' + obj('ta_title').value + '</h2></td></tr>';
html += '<tr><td>&nbsp;</td></tr>';
html += '<tr><td align="center">Each Round Results</td>';
html += '</table>';
html += '<div id="button" style="width:760px;margin-top:20px;margin-bottom:20px;"><input type="button" value="Print" onmouseup="window.print()" style="float:right;" /></div>';
html += '<table width="760" align="center" border="0">';
html += '<tr>'
html += '<td><b><u>Winner:</b></u></td>';
html += '</tr>';
html += '<tr><td>';
for (i = 0; i < winnerArray.length; i++) {
    temp = winnerArray[i].split('|', 3);
    vote = temp[0];
    name = temp[1];
    round = temp[2];
    html += '(The' + num2Chi(round) + 'Round) ' + name + ' ' + vote + 'Votes' + '<br />'; 
}
html += '</td></tr>';
html += '<tr><td>&nbsp;</td></tr>';
html += '<tr>'
html += '<td><b><u>Detail Voting Result:</b></u></td>';
html += '</tr>';
html += '<tr><td>';

for (i = 0; i < wholeArray.length; i++) {
    w_temp = wholeArray[i].split('|', 4);
    w_vote = w_temp[0];
    w_name = w_temp[1];
    w_round = w_temp[2];
        html += '<font color="red">(The' + num2Chi(w_round) + 'Round) ' + w_name + ' ' + w_vote + ' Votes </font><br />';
}
html += '</td></tr>';

html += '</table>';
html += '</body>';
html += '</html>';
var x = window.open('', 'printList', "location=0,menubar=0,scrollbars=1,status=0,toolbar=0,resizable=1,width=800,height=600");
x.document.write(html);
x.document.close();
}

Answer №1

To efficiently calculate the percentages, utilize two separate loops: one to tally up all votes and store them in a sum variable, and another to determine the percentage of each option.

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

Autofill with JavaScript - Dynamic Form Population

Looking to create a form-based HTML page. The objective is to have the second input box automatically populate based on the user's input in the first input box. I've gone through various guides and tried to implement this script, but it doesn&ap ...

Issue with React Native Hook where converting a function into a class variable results in 'undefined'

We are currently in the process of converting a react native function into a class so that we can implement state management compatible with Firebase's real-time database. It recently came to our attention that Hooks cannot be used within a class, so ...

Determine the initial and final non-zero elements/indices in a group using numpy

import numpy as np group = np.array([0,0,0,0,1,1,1,1,1,1,2,2,2,2]) array = np.array([1,2,3,0,0,2,0,3,4,0,0,0,0,1]) targt = np.array([1,1,1,0,0,2,2,2,2,0,0,0,0,1]) def func(group: np.array, array: np.array): pass return array Step 1: Ident ...

Executing gruntfile from the devDependencies module

Currently, I am testing out a .js framework. Within my package.JSON file, specifically inside devDependencies, I have the following: "devDependencies": { "myFramework": "https://github.com/myRepo/myFramework/tarball/master", "grunt": "~0.4.2", ...

Save various uploads according to their designated folders in the MySQL database

After browsing through several similar questions to mine, I realized that I need to change the way I am currently storing files in the database. In my first file (getPic.php), I have a form like this: <form enctype="multipart/form-data" method="POST" ...

How can the ID of a table row be retrieved if it is selected?

In my datatable, I have a list of Cars where each row contains a Car ID. A checkbox column has been added to the first cell in the table - when checked, the row is highlighted to show the user their selection. The goal is to retrieve the IDs of all selecte ...

Picasso encountered a problem when trying to process a list of images

While working on parsing a list of images from JSON data and displaying them using Picasso based on user click position, I encountered this error: FATAL EXCEPTION: main java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0 at java.util ...

Is it possible to specify a static callback function name when making a JSONP request using jQuery?

The jQuery documentation provides an example of how to make a JSONP request using $.getJSON: $.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?", function(data) { $.each(data ...

Creating pagination in an AngularJS application can be achieved by using the ng-repeat directive along with the

Can anyone help me with implementing uib-pagination? I have data stored in $scope.event and I want to display pagination based on this data. However, the pagination directive is not showing up. I don't see any errors in the console. Any insights on wh ...

Having difficulty updating an angular variable within a callback function

Currently, I am utilizing the Google Maps directions service to determine the estimated travel time. this.mapsAPILoader.load().then(() => { const p1 = new google.maps.LatLng(50.926217, 5.342043); const p2 = new google.maps.LatLng(50.940525, 5.35362 ...

Learn how to implement the JQuery ReplaceWith function with the resources provided by materials.io icon

I would like the favorite_border icon to switch to the favorite icon when clicked. As we are using material.io and both icons have the class material-icons, I am unsure about how to implement this using jQuery. What steps should I take to achieve this? (w ...

CodeIgniter 3 fails to handle jQuery ajax calls

I am currently tackling an ajax request issue in CodeIgniter 3. The task involves clicking on a checkbox to trigger the changVisib() function. Upon reviewing the code snippet, everything appears to be functioning correctly as the alert() is being executed. ...

Getting the name and value from an object

Just starting out with Javascript and Nodejs, using express and making a call to the following link: localhost:7080/v1/movies/order/notify/insert?breed=Whippet&age=10 After that, I am attempting to extract the property name along with its correspon ...

Navigating C pointers with casting types

#include<stdio.h> int main() { int a; char *x; x = (char *) &a; a = 512; x[0] = 1; x[1] = 2; printf("%d\n",a); return 0; } I'm struggling to understand how the output ends up being 513 or if i ...

Angular sends a POST request using $http to open in a new tab

In my Angular application, I am trying to send a POST request to a URL ./makeFile.php. This request will create a file with contents retrieved from a database query based on the data provided in the POST. When using PHP, the browser automatically opens a ...

Covering and disguising AJAX requests

I am revisiting a question I posted several weeks ago. The code snippet below includes an HTML 4.01 Transitional document with inline JavaScript: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.d ...

Performance issues arise when rendering multiple DataTable's simultaneously

I have a web application that requires frequent redrawing of DataTable instances. Each instance has a very small datasource, but during performance testing of a typical instance, I found that it took 200ms. var table = $("#Table").DataTable({ "data": ...

FancyBox - Is there a "Never show this message again" option available?

I implemented FancyBox on my website to display important information to users. However, I would like to enhance the user experience by adding a button that allows them to set a cookie and prevent the message from popping up for about a month. Since I&apo ...

The error has not been handled properly and is being thrown at line 174 in the events.js file

I encountered an issue while trying to request data from an API, resulting in a crash on any Windows server. Can someone lend a hand with this problem? Here is a snippet of my code: app.get("/js/2806/api/products/getAllDrugs", (req, res) => { co ...

What is the best way to manage global data in AngularJS?

Is it considered a best practice to store user data, such as profile name, in the $rootScope in AngularJS when it needs to be accessed in multiple routes? If not, what is the recommended approach for storing this type of information? ...