0

I need to group the rows out of a table that has a matching order number, and then iterate over the groupings.

I have this code working which is creating the perfect array, data-wise:

    var multItems = [];
    // Combine items under orders,
    $('tr.order').each(function(){
        var orderNum = $(this).find('.ordernumber').val();
        if ( ($('tr.order .ordernumber[value="' + orderNum + '"]').length > 1 ) && !(orderNum in multItems) ){
            $('tr.order .ordernumber[value="' + orderNum + '"]').each(function(){
                if (!(orderNum in multItems)){
                    multItems[orderNum] = [];
                }
                multItems[orderNum].push(this);
            });
        }
    });
    // Create new tr with order totals (of each item)
    for (var i = multItems.length - 1; i >= 0; i--) {
        // Code
    };

But it creates an array with a length of 0, apparently, where multItems = [], but multItems[orderNumber] is defined... just with no way to access it if I don't know the order numbers.

I could make an array of the order numbers separately, but that feels like it must be the long way round. If I just create a numbered array, how do I know which number to pop the items from the orders into?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Damon
  • 10,493
  • 16
  • 86
  • 144
  • Right now `orderNum` is a string, using `parseInt`, or even `push()` if possible, would solve a few issues if it is in fact a number indexed array you're trying to create. – adeneo Mar 25 '13 at 21:48
  • @adeno—orderNum will be coerced to string anyway, even it was a number, so that isn't the issue. – RobG Mar 25 '13 at 22:59
  • @Damon—in the question you have "but `multItems[orderNumber]` is defined" but in the code you have `multItems[orderNum]`, which is it? – RobG Mar 25 '13 at 23:04

1 Answers1

2

With your current code you have

var orderNum = $(this).find('.ordernumber').val();

where val() returns a string and not a number. So when you are doing multItems[orderNum] it is a string.

For the current code to work, you want to use a for in loop.

for (var prop in multItems) {
    if( multItems.hasOwnProperty( prop ) ) {
        console.log(multItems[prop]);
    }
}

FYI: Order is not guaranteed. Also you should be using an object {} and not an array here.


Now the other thing you can do is to use parseInt to change the string into a number and than magically your for loop would start working. [This is assuming that ordernumber is a numeric value]

var orderNum = parseInt($(this).find('.ordernumber').val(), 10);
epascarello
  • 204,599
  • 20
  • 195
  • 236
  • Array indexes are just object properties (i.e. strings), so if `orderNum` was a number it would be coerced to string anyway. – RobG Mar 25 '13 at 22:54