Onilol Onilol - 6 months ago 9
Javascript Question

Loop through specific indexes in array

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

Answer

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]];
}