0

I am creating an array with the below code.

The single functions work fine so far, my only problem with the loop is how to create the variables (nameX and dataX) dynamically from each item in the array.

Example: My array is [item1,item2,item3]. In this case the variables should be name1, data1, name2, data2, name3, data3 (nameX and dataX are just placeholders here for now).

My code:

//get unique items
var inputSearch = new Array();
$('td.searchTerm').each(function() {
    if( ($(this).text() != '') && ($(this).text() != ' ') ) {
        if(inputSearch.indexOf($(this).text()) == -1) {
            inputSearch.push( $(this).text() );
        }
    }
});

//loop through array to get volumes per item
var i;
for (i = 0; i < inputSearch.length; i++) {
    var nameX = inputSearch[i].replace(/\s+/g, '');
    var dataX = [];
    var xSum = 0;
    $('#myTable tbody tr').each(function() {
        if ($(this).find('td:contains(' + nameX + ')').length === 0) {
            dataX.push(0);
        } else {
            xSum = 0;
            $(this).find('td:contains(' + nameX + ')').each(function() {
                 xSum += parseInt($(this).next('td').text());
            });

            dataX.push(xSum);
        }
    });
}

Update: I found a way to create the name variable dynamically, so now only the data variable is missing:

window['name' + i.toString()] = inputSearch[i].replace(/\s+/g, '');

Many thanks for any help with this, Tim.

user2571510
  • 11,167
  • 39
  • 92
  • 138
  • *"In this case the variables should be name1, data1, name2, data2, name3, data3"* - You most definitely don't want that. – Tomalak Apr 07 '14 at 10:25
  • It doesnt matter how they are called but they need to be named different so that they dont overwrite each other. – user2571510 Apr 07 '14 at 10:36
  • You still don't want that. You never want to use numbered variables of any kind, especially not a variable amount of them. That's what arrays are for. – Tomalak Apr 07 '14 at 10:37
  • Thanks for telling me what I don't want. I would rather have some advise on how to fix this. – user2571510 Apr 07 '14 at 10:40
  • I could tell you how to fix it if you told me what you actually intend to do. So far you've only told me that you want to create dynamic variables with a counter suffix, and all I can say to that is that that's completely the wrong thing to want. – Tomalak Apr 07 '14 at 10:42
  • 1
    Please add as to what purpose you want the "numbered" variables, so perhaps we can help solve it using an array. An array in essence is exactly that, numbered variables, just that their name is array[x] – Yoav Schwartz Apr 07 '14 at 10:44
  • Thanks. I thought I did that in my post. The 1st part is an array which goes through a table and creates a list with the unique items from this table. The 2nd part is a function that creates an array with the values that appear in the cells next to the above items. Both of this works fine if fill in the variables manually which is why I would like to do this automatically with a loop. – user2571510 Apr 07 '14 at 10:45
  • @ Yoav: Thanks ! It doesnt have to be numbered variables, I just need anything to differ between them so that a variable doesnt get overwritten when looping through the array. They could also be called nameA, nameB, nameC or whatever else works here. – user2571510 Apr 07 '14 at 10:47
  • You are way too fixed on that variables thing. This is not the right approach and you must let it go. State your intent, i.e. *"I want a list of unique search terms and a sum next to each one."*. The *what* you want is important, not the *how* you want to solve it. – Tomalak Apr 07 '14 at 11:09
  • 1
    I need two things: A list of unique items (currently my first array) + a list of the values next to these items (currently my second array). Both of these are required as separate lists, not combined in one. – user2571510 Apr 07 '14 at 11:29
  • Ah, *that's* the right way to state your intent. — I don't quite understand the "needs to be separate" requirement, but building two arrays and filling them in parallel should be easy enough. This way `names[i]` would correspond to `values[i]` for any given `i`. – Tomalak Apr 07 '14 at 11:37

1 Answers1

1

As I said in the comments, don't try to create "variable variables". Only pain and suffering lies down that path.

Here is a way to solve what you seem to be trying without resorting to ugly hacks.

var searchTerm = {};

$('td.searchTerm').each(function () {
    var term = $.trim( $(this).text() ), 
        name = term.replace(/\s+/g, '_');

    // prevent empty or non-unique entries
    if ( !term || searchTerm.hasOwnProperty(term) ) return;

    // sum up table values for the current term
    searchTerm[term] = 0;
    $('#myTable tbody td:contains(' + name + ')').each(function () {
        searchTerm[term] += parseInt( $(this).next('td').text(), 10 );
    });
});

Would give you something like this:

searchTerm = {
    "foo": 10,
    "bar": 20,
    "baz": 0
};

Think about handling mixed case appropriately. Currently foo and Foo are different terms, which might or might not be what you need.

There is an easy way to extend jQuery with a case-insensitive :contains selector.

Community
  • 1
  • 1
Tomalak
  • 332,285
  • 67
  • 532
  • 628
  • Thanks. Is there a way I can access the numbers (10, 20, 0) out of this array ? I need these separated from the item names. – user2571510 Apr 07 '14 at 12:48
  • What's wrong with filling a separate array, the way I indicated it in my comment to your question? – Tomalak Apr 07 '14 at 12:51