I have a table with products and it's variants.
Each one has an index on the table, for instance:
[0] Product 1
[1] Variant 1
[2] Variant 2
[3] Product 2
etc..
I've assigned to an associative array all the variant's indexes along with their value, for instance:
[1] Variant 1 : 13
[2] Variant 2 : 15
[18] Variant 3: 32
Now I want to loop through the table using only the indexes I got on my array.
Is there a way to loop through an element using specific indexes? ( So I don't have to loop through the whole thing and execute what I want whenever it matches ). Something similar to this pseudocode:
loop through my_table on index = [1,2,18]
Edit for Joseph Marikle:
The code part for the array is this:
var variants_index = [];
$.each($('.variant'),function(){
variants_index[$(this).index()] = $(this).find('td').eq(1).text();
});
typing typeof(variants_index) we get: object and typing the var in the console, we get Array and, typing Array.isArray(variants_index) we get true
2 Answers 2
You can loop through your array of indices that you are interested in and use their values as an index to your array containing product info.
var indexToCheck = [1,2,18];
for(var i = 0; i < indexToCheck.length; i++){
var productInfo = myProducts[indexToCheck[i]];
}
Comments
loop through my_table on index = [1,2,8] (changed the 18 to 8 for simplicity)
Since that's the core of the problem, let's try to solve it.
index = [1,2,8]
my_table = [5,4,6,7,3,8,2,9,0,1]
for (i=0;i<index.length;i++){
console.log(my_table[index[i]]);
}
This would get the numbers from "index" as use them as indexes to access positions in my_table
typeofagainst an array will always return "object" in javascript. To test if a variable holds an array, you should useArray.isArray(obj). Your scenario is as I described in my first comment. Both answers below are how I would accomplish what you're trying to do.