Analyze the individuals listed in one column of the table and calculate the total from the adjacent column using JavaScript

I have a table with participant data that I would like to compare. If a participant has multiple result points in the table, I want a script to calculate the sum of all their results. This process should be repeated for each participant listed in the table. The table is generated from a database field which includes columns for Participant, Station, and Points:

aa  Some1   1
dd  Some1   2
aa  sm2    3
dd  sm2    4
bb  sm3    5
ee  sm3    6

For example, I need to create a new table with the summed results per participant:

aa - 4,
dd - 6,
bb - 5,
ee - 6

I've attempted to achieve this with the following code snippet:

$(document).ready(function () {
    $("body").click(function () {

        var rows = $("tbody tr");
        var jo = [];

        for (var i = 0; i < rows.length; i++) {

            for (var j = 1; j <= rows.length; j++) {

                var pnt1 = $(rows[i]).find(".pnt").html();
                var stations1 = $(rows[i]).find(".station").html();
                var res1 = $(rows[i]).find(".res").html();

                if (pnt1 == $(rows[j]).find(".pnt").html()) {
                    res1 = parseInt(res1);
                    res2 = parseInt($(rows[j]).find(".res").html());
                    jo.push(pnt1, res1, res2);
                    break;
                }

            }

        }

        console.log(jo);

    });
});

However, it seems I may be going about this the wrong way. Any assistance or guidance on solving this issue would be greatly appreciated.

Updated section based on comments:

<table id="pntsRes">
<thead>
<tr>
    <th>Participants</th>
    <th>Points</th>
</tr>
</thead>
<tbody>
<tr><td class="pnt">aa</td><td class="station">AES</td><td class="res">1</td></tr><tr><td class="pnt">dd</td><td class="station">AES</td><td class="res">2</td></tr>
<tr><td class="pnt">aa</td><td class="station">Science</td><td class="res">3</td></tr>
<tr><td class="pnt">dd</td><td class="station">Science</td><td class="res">4</td></tr><tr><td class="pnt">bb</td><td class="station">Airport</td><td class="res">5</td></tr>
<tr><td class="pnt">ee</td><td class="station">Airport</td><td class="res">6</td></tr></tbody>
</table>

Answer №1

In order to enhance the maintainability of your code, a suggested approach would be to break down your solution into three separate functions. The first function could focus on extracting data from the HTML, although this practice is somewhat questionable. The second function could then handle transforming the extracted data, and the final function could deal with outputting the new table.

function extractData() {
    var rows = $("tbody tr");
    var data = [];
    rows.each(function(index, row) {
        var point = $(row).find('.point').html();
        var station = $(row).find('.station').html();
        var result = parseInt($(row).find('.result').html());
        data.push([point, station, result]);
    });
}

For the transformation process, you could consider utilizing a method similar to the one outlined below:

// Utilize the output from extractData() for further processing
function processData(data) {
    var groupedKeys = {};
    var transformedData = data.map(function(datum) {
        var name = datum[0];
        var value = datum[2];
        groupedKeys[name] = (groupedKeys[name] || 0) + (value || 0);
    });

    var formattedData = [];
    Object.keys(groupedKeys).forEach(function(key) {
        formattedData.push([key, groupedKeys[key]]);
    });

    return formattedData;
}

The implementation of the final function would be left to your discretion, offering opportunities for improvement. Nevertheless, these suggestions may serve as a solid foundation for enhancements in your code structure.

Answer №2

To solve this problem, I utilized an associative array, which is essentially an object in JavaScript. Here is the modified code snippet:

http://jsfiddle.net/a5k6w300/

Key Changes:

var jo = [];

was replaced with an object instead of an array as shown below:

var jo = {};

Additionally, I included the 'if(isNaN(object[key])' condition inside the inner loop to ensure that the values did not turn into NaN during summation.

$(document).ready(function () {
    $("body").click(function () {

        var rows = $("tbody tr");
        var jo = {};
console.log(rows);
        for (var i = 0; i < rows.length; i++) {

            for (var j = 1; j <= rows.length; j++) {

                var pnt1 = $(rows[i]).find(".pnt").html();
                var stations1 = $(rows[i]).find(".station").html();
                var pntR1 = $(rows[i]).find(".res").html();
                if (pnt1 == $(rows[j]).find(".pnt").html()) {
                    pntR1 = parseInt(pntR1);
                    pntR2 = parseInt($(rows[j]).find(".res").html());
                    if(isNaN(jo[pnt1])){
                        jo[pnt1] = 0;
                    }
                    jo[pnt1] += pntR1;
                    break;
                }

            }

        }
        console.log(jo);

    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="pntsRes">
    <thead>
        <tr>
            <th>Participants</th>
            <th>Points</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td class="pnt">aa</td>
            <td class="station">AES</td>
            <td class="res">1</td>
        </tr>
        <tr>
            <td class="pnt">dd</td>
            <td class="station">AES</td>
            <td class="res">2</td>
        </tr>
        <tr>
            <td class="pnt">aa</td>
            <td class="station">Science</td>
            <td class="res">3</td>
        </tr>
        <tr>
            <td class="pnt">dd</td>
            <td class="station">Science</td>
            <td class="res">4</td>
        </tr>
        <tr>
            <td class="pnt">bb</td>
            <td class="station">Airport</td>
            <td class="res">5</td>
        </tr>
        <tr>
            <td class="pnt">ee</td>
            <td class="station">Aerodrome</td>
            <td class="res">6</td>
        </tr>
    </tbody>
</table>

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

Combining associative arrays by utilizing a mapping array along with an array containing partial keys (providing support for named parameters)

Exploring a new template system I am creating, one that specifically caters to named parameters in template filters and functions. Let's cut to the chase and address the issue at hand using my escapeHtml filter, which essentially mirrors htmlspecialc ...

Having trouble receiving values sent through AJAX POST requests to PHP

Can anyone help me figure out why my AJAX POST method is not sending the specific section of my URL string to my PHP file? I've checked everything and can't seem to find where the issue lies. When I var_dump the POST variable in my PHP file, it s ...

What is the best way to trigger a controller action when the datepicker's value changes?

Hello, I have a custom datepicker and I am trying to perform a calculation when the year is changed. The code provided below does not seem to work on onchange. I also attempted using the onchange attribute and calling a JavaScript function like this oncha ...

I need help figuring out the proper way to establish an indexing path in cosmos db using the nodejs sdk

I'm currently facing a challenge with setting up the indexing policy for one of my cosmosdb containers. Within my cosmosdb, I have a container that stores information about user sessions. Using the node sdk, I am defining the containers, partition key ...

Creating a tree array in JavaScript from JSON data

I have been struggling to create a tree array from the given JSON data. I have attempted to use filter, map, and reduce methods, but haven't been successful in achieving the desired result. [{ "code": "2", "name": "PENDING" },{ "code": "2.2", ...

Creating a Multidimensional Dynamic Array: A Step-by-Step Guide

I'm new to MQL4 coding and currently working on my first EA. I've recently discovered Arrays and now I'm interested in coding a Multidimensional Dynamic Array. My goal is to analyze the past 100 bars, identify the highest 50 bars, save and l ...

Activate the ajax function using a specific reference

I have been working on creating an ajax function that contains all the data inside the variable called $item within the following function: public function handleAjaxData(&$item,&$params,$limitstart) { $view = JRequest::getVar('view' ...

Sending information to a Flask application using AJAX

Currently, I am working on transferring URLs from an extension to a Flask app. The extension is able to access the current URL of the website. I have set up an AJAX request to connect to Flask, and the connection is successful. However, when trying to send ...

Error in test runner: Cannot convert type 'Cucumber' to type '? extends Runner' in Java cucumber

I'm currently working on setting up the Cucumber framework using Java for running my tests, but encountering a type mismatch error in the Test Runner. package cucumbertest; import org.junit.runner.RunWith; import cucumber.api.CucumberOptions; import ...

Deleting query strings from the URL - HashRouter

In my application, I have a LoginContainer component that houses both a login-form and a signup-form. These components are displayed on the same page, with only one of them being rendered based on user interaction. While the functionality of the forms is ...

Filter through the array of objects using the title key

I'm attempting to extract specific data by filtering the 'page_title' key. Below is a snippet of my JSON object: { "page_components": [ { "page_title": "My Account", "row_block": [ { "heading": "", "sub_headi ...

Using React Higher Order Components to transmit data attributes to the initial child/element within the encapsulated component

Presently, I have a custom higher-order component structured in the following manner: export const withAttrs = (WrappedComponent) => { const ModifiedComponent = (props) => ( <WrappedComponent {...props} data-test-id="this-is-a-element&q ...

Update the specific component according to the identified modifications

In my project, I have two simple components: parent and child. The parent component contains an Array and for each element in the array, it renders the child component. parent.component.ts export class parent implements OnInit { data: CustomType[] = [ ...

PHP-generated AngularJs Select Element

I'm facing an issue with my PHP function in my AngularJS application. I have created a function to select a default option, but it's not displaying the desired value. Here is the function code: function qtyList($selectName, $selectQty){ $st ...

Is it possible to utilize a JS script generated within the body or head of an HTML file directly within CSS code?

As a beginner in webpage development, I have a query regarding the technical aspect. Is it possible to utilize variables from a JavaScript function, which is placed either in the head or body of an HTML file, directly in CSS code to make modifications such ...

Understanding the Fundamentals of Arrays

#include<iostream.h> main() { int a[10]; return 0; } What is the rationale behind array indices starting at zero rather than one? Looking for a logical explanation! ...

Restrict the Angular ng-repeat directive to specific rows only

Suppose we have a JSON dataset listing all languages of books: $scope.data = [{ "title": "Alice in wonderland", "author": "Lewis Carroll", "lang": ["en"] }, { "title": "Journey to the West", "author": "Wu Cheng'en", "lang": [" ...

Having trouble accessing variable values within the nth-child selector in JavaScript

I am attempting to utilize the value of a variable within the element selector p:nth-child(0). Instead of hardcoding the number as 0, I want to dynamically assign the value of a variable. In this case, the variable is represented by i in a for loop. Howev ...

Access the current slide number with the slideNumber feature in Reveal.js

Can someone assist me with Reveal.js? Could you explain how I can retrieve the current slide number and store it in a variable? I am looking to add an event on my fourth slide. Thank you for your help! ...

What is the best way to display the shape value of a tensor?

I utilized the function print tf.shape(image) The result appears as follows Tensor("Shape:0", shape=(3,), dtype=int32, device=/device:CPU:0) I am interested in knowing the values within the shape (such as the dimensions). How can I retrieve and display ...