Kunal Ojha Kunal Ojha - 5 months ago 10
Javascript Question

How can I print items in an array in numerical order?

I have a for loop that pushes items into an array if they pass a certain condition. I then output each item of its respective array so that it's displayed in an iteration in a table structure:

var row = "";
var CatNum = [];
var Org = [];
var tooltip = {
cat1: '',
cat2: ''
};


for loop:

for (var i = 0; i < data.length; i++)
{
if (data[i].catType === 'I')
{
CatNum.push(data[i].catNum);
Org.push(data[i].org);
trackingNumber.push(data[i].trackingNumber)

row = '<tr>' +
'<td class="tooltip-Val">' + <NUMERICAL ORDER HERE:> + Org[i] + '</td>' +
'</tr>';

tooltip.cat1 = tooltip.cat1.concat(row);
}

else if (data[i].catType === 'II')
{
CatNum.push(data[i].catNum);
Org.push(data[i].org);
trackingNumber.push(data[i].trackingNumber);

row = '<tr>' +
'<td class="tooltip-Val">' + <NUMERICAL ORDER HERE:> + Org[i] + '</td>' +
'</tr>';

tooltip.cat2 = tooltip.cat2.concat(row);
}


What I'd like to do is order each iteration in numerical order.

Right now i don't have a method for numbering each loop that gets printed.
My goal is to have the HTML print like so:

CATI :
1. xxxxx

2. xxxxx

3. xxxxx

CATII :
1. yyyyy

2. yyyyy


Any ideas on the best way to do this?

Answer

Increment variables initially set to 0 if if or else if condition is true

for (var i = 0, cat 1 = 0, cat2 = 0; i < data.length; i++) {
  if (data[i].catType === 'I') {
    CatNum.push(data[i].catNum);
    Org.push(data[i].org);
    trackingNumber.push(data[i].trackingNumber)

    row = '<tr>' 
      // increment `cat1`
      + '<td class="tooltip-Val">' + (++cat1) + Org[i] + '</td>'
      + '</tr>';

    tooltip.cat1 = tooltip.cat1.concat(row);
  } else if (data[i].catType === 'II') {
    CatNum.push(data[i].catNum);
    Org.push(data[i].org);
    trackingNumber.push(data[i].trackingNumber);
    // increment `cat2`
    row = '<tr>' + '<td class="tooltip-Val">' + (++cat2) + Org[i] 
      + '</td>' 
      + '</tr>';

    tooltip.cat2 = tooltip.cat2.concat(row);
  }
}