Hi,

I have an array of integers

I like to retrieve the max number and index of max number from that array without using Math.Max() function..

Presently in this below code, I have 4 dynamic values, end user will be select degree from combo box, entering the values semester, Max marks and Obtained marks as numeric values. Once entered dynamic rows will be created and it also calculate the percentage by the formula (om/mm)*100 for each row on clicking Sum and it also creates new column…

I needed to have code when the degree changes only.. it should calculate the sum of all max.marks and Obtained marks of each semester and then calculate percentage by above formula… and also new column should not be created…..Please sort with max marks… Please help me in this regard… Thank you for helping me initially.

what is the easiest way...


Cheers
Santhosh

function insRows()
{
    var x = document.getElementById('finalMarks').insertRow();
    var cell = x.insertCell(0)
    var a = x.insertCell(1);
    var b = x.insertCell(2);
    var c = x.insertCell(3);
    var d = x.insertCell(4);
    var element1 = document.createElement("input");
        element1.type = "checkbox";
        cell.appendChild(element1);
    a.innerHTML = document.getElementById('txtqualify').options[document.getElementById('txtqualify').selectedIndex].text
    b.innerHTML = document.getElementById('txtsem').value
    c.innerHTML = document.getElementById('txtmaxmrk').value
    d.innerHTML = document.getElementById('txtobtmrk').value
}

function function1()
{
   var myRow = document.all.finalMarks.rows.length;
   var ed='';
   var mm=0,om=0, x,z;
   for(i=0;i<myRow;i++)
   {
        r = document.all.finalMarks.rows[i];
    pr = r.cells[1].innerHTML
    mm+= parseInt(r.cells[3].innerHTML)
    om+= parseInt(r.cells[4].innerHTML)
    if (pr!=ed && ed!='')//(i==myRow-1)
        {
            prevr = document.all.finalMarks.rows[i-1];
            mycurrent_cell = document.createElement("td");
            mm-= parseInt(r.cells[3].innerHTML)
            om-= parseInt(r.cells[4].innerHTML)
            z = (om/mm)*100
            mycurrent_cell.innerHTML = z
            mm= parseInt(r.cells[3].innerHTML)
            om= parseInt(r.cells[4].innerHTML)
            alert(mycurrent_cell.innerHTML  +   '['  + pr + ']' + ed)
            //alert(!isNaN(mycurrent_cell.innerHTML))
            if(!isNaN(mycurrent_cell.innerHTML))
            {
                qualary[qualary.length] = prevr.cells[1].innerHTML
                pctary[pctary.length] = mycurrent_cell.innerHTML
                prevr.appendChild(mycurrent_cell);
                mycurrent_cell.innerHTML = z;
                document.getElementById('txtpert').value = z
             }
        }
        ed = r.cells[1].innerHTML
        alert(ed)
        if (i==myRow-1)
    {
            prevr = document.all.finalMarks.rows[i];
            //mycurrent_cell = document.createElement("td");
            x = (om/mm)*100
            mycurrent_cell.innerHTML = x
            qualary[qualary.length] = prevr.cells[1].innerHTML
            pctary[pctary.length] = mycurrent_cell.innerHTML
            prevr.appendChild(mycurrent_cell);
            if(!isNaN(x))
            document.getElementById('txtperct').value = x
        }
    }
    //document.frmMarks.txtper.value = Math.max( x, z)
    var str = sortAndReturn(pctary,qualary)
    //alert(pctary  +   '$'   + qualary)    //alert(sortAndReturn(pctary,qualary))
    //alert(str)    //alert(str[0]+','+str[1])
     document.getElementById('degr').value = str.split('$')[0]
     document.getElementById('txtmarks').value = str.split('$')[1]
}
function sortAndReturn(pctary,qualary)
{
    var myArray3 = new Array();
    for(i=0;i<pctary.length;i++)
    myArray3[i]=pctary[i];
    sort(pctary)
    //alert(sort(pctary))    //alert(myArray3)
    return qualary[indexSearch(myArray3,pctary[0])] + '$' + pctary[0]
}
function sort(a)
{
    var  max;
    for(i=0;i<a.length;i++)
    {
        max   =  i;
        for(j=i+1;j<a.length;j++)
    {
            if (a[j]>a[max])
            {
        max=j;
            }
    }
    //alert(a[max])
        if (i != max)
        {
            var swap = a[i];
            a[i] = a[max];
            a[max] = swap;
        }
    }

}
function indexSearch(a,b)
{
    for(i=0;i<a.length;i++)
    if(a[i]==b)
    {return i ;}
}

HTML CODE:

<table BORDER ="6"  width="85%"align="center" bgcolor="#00FFFF"  style="font-family: Verdana;color: black;font-size: 12px">
                <tr>
                    <td align="center" width="25%" height="40"> Qualification:</td>
                    <td align="left" style="WIDTH:25%" >
                    <select id ="txtqualify" style ="width:150px;height:25px" name ="txtqualify"  > </select> </td>
                    <td align="center" width="25%" height="40">Semester:</td>
                    <td> <input type = "text" SIZE="8" maxlength = "3" id = "txtsem" name = "txtsem"> </td>
                </tr>
                <tr>
                    <td align= "center" width ="25%" height="40">Max.Marks:</td>
                    <td> <input type = "text" SIZE="8" maxlength = "3" id = "txtmaxmrk" name = "txtmaxmrk"> </td>
                    <td align= "center" width ="25%" height="40">Obtained.Marks:</td>
                    <td> <input type = "text" SIZE="8" maxlength = "3" id = "txtobtmrk" name = "txtobtmrk"> </td>
                </tr>
                <tr>
                    <td align= "center" width ="25%" height="40">Percentage:</td>
                    <td> <input type = "text" SIZE="8" maxlength = "5" id = "txtper" readonly name = "txtper">
                    <td align="center" colspan="4" valign="middle">
                        <input type="RESET" align="middle" style="width:20%" value="ADD"  onclick="insRows()" >
                         <input type="button" align="middle" style="width:20%" value="REMOVE" onclick="delRow()" >
                         <input type="button" align="middle" style="width:20%" value="CLOSE" onclick="" >
                         <input type="button" align="middle" style="width:20%" value="SUM" onclick="function1()" >
                    </td>
                    </tr>
                <tr>
                    <td  align="center" height="40"> <input type = "text" SIZE="8" maxlength = "5" id = "txtpert" name = "txtpert"> </td>
                    <td align="center"> <input type = "text" SIZE="8" maxlength = "5" id = "txtperct" name = "txtperct"> </td>
                    <td align="center"> <input type = "text" SIZE="10" maxlength = "5" readonly id = "degr" name = "degr"> </td>
                </tr> 
            </table>
            <table id ="finalMarks" BORDER ="6" width="85%"align="center" bgcolor="#00FFFF"  style="font-family: Verdana;color: black;font-size: 12px">
                <thead>
                    <th height="40">Remove</th>
                    <th>Qualification</th>
                    <th>Sem/Year</th>
                    <th>Max.Marks</th>
                    <th>Obt.Marks</th>
                    <th>Percentage of Marks:</th>
                </thead>
            </table>

Dani AI

Generated

— treat each table row as a record, group rows by Qualification, sum the Max.Marks and Obt.Marks per group, compute the percentage per group (totalObt / totalMax * 100), and then pick the group with the highest percentage. 's scan idea is fine, but avoid extending Array.prototype in production; a local pass (or reducer) is safer and easier to reason about. The snippet below shows a compact, safe approach that does not add any new table columns and can be called when the degree (qualification) changes.

function computeGroupTotalsAndTop() {
  const rows = Array.from(document.querySelectorAll('#finalMarks tr'));
  const groups = Object.create(null);

  rows.forEach(row => {
    if (row.querySelector('th')) return;            // skip header
    const c = row.cells;
    if (!c || c.length < 5) return;
    const qual = (c[1].textContent || '').trim();
    const max = Number((c[3].textContent || '').trim());
    const obt = Number((c[4].textContent || '').trim());
    if (!groups[qual]) groups[qual] = { totMax: 0, totObt: 0 };
    groups[qual].totMax += isFinite(max) ? max : 0;
    groups[qual].totObt += isFinite(obt) ? obt : 0;
  });

  const results = Object.keys(groups).map(q => {
    const g = groups[q];
    return { qual: q, percent: g.totMax > 0 ? g.totObt / g.totMax * 100 : NaN, totMax: g.totMax };
  });

  if (!results.length) return;
  let top = results[0];
  for (let i = 1; i < results.length; i++) if ((results[i].percent || -Infinity) > (top.percent || -Infinity)) top = results[i];

  document.getElementById('degr').value = top.qual || '';
  document.getElementById('txtmarks').value = isFinite(top.percent) ? top.percent.toFixed(2) : '';
  document.getElementById('txtperct').value = document.getElementById('txtpert').value = isFinite(top.percent) ? top.percent.toFixed(2) : '';
}

function sortByMaxMarksDescending(tableId) {
  const table = document.getElementById(tableId);
  if (!table) return;
  const body = table.tBodies[0] || table;
  const rows = Array.from(table.querySelectorAll('tr')).filter(r => !r.querySelector('th'));
  rows.sort((a, b) => Number((b.cells[3] && b.cells[3].textContent) || 0) - Number((a.cells[3] && a.cells[3].textContent) || 0));
  rows.forEach(r => body.appendChild(r)); // reorders existing rows, no new columns
}

Hook the calculator to the qualification select: document.getElementById('txtqualify').addEventListener('change', computeGroupTotalsAndTop), and call sortByMaxMarksDescending('finalMarks') when you want to reorder rows by Max.Marks. Quick tips: use Number() or parseFloat() (not parseInt without a radix), always check isFinite before dividing, read text with textContent (not innerHTML), and re-run the helper after any add/remove so totals stay correct.

Recommended Answers

All 2 Replies

hm.... I do not see any problem to get max number from array. Usually I use following function

Array.prototype.max=function()
{
	if (this.length == 0)
		return {'index':-1};
	var maxIndex = 0;
	for (var i = 1; i<this.length; i++)
		if (this[i]>this[maxIndex]) 
			maxIndex = i;
	return {'index':maxIndex, 'value':this[maxIndex]};
}

It returns index and value of max array item or index=-1 if array is empty

Hi Vitana,

Thank you for replying..
I request to provide code for sorting and to find max no in an dynamic array if possible to sort it out this problem

Regards,
Santhosh

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.