Reputation: 1175
Imagine you have a product page. On this page there are two select inputs with options in them.
There is one for Size and Colour. This can change depending on the product, e.g. a curtain might have a size, length and colour (three select menus).
The array is created dynamically (based on each select menu and its options):
var dynamicArr = [],
i,
j,
opt,
$('.select');
for (i = 0; i < select.length; i += 1) {
opt = select.eq(i).find('option');
if (dynamicArr[i] === undefined) {
dynamicArr[i] = [];
}
for (j = 0; j < opt.length; j += 1) {
dynamicArr[i].push(opt.eq(j));
}
}
Imagine the page had a size and colour drop-down. The above would create an array like this:
dynamicArr = [['size'], ['color']]
I want to loop through each of these separately (in order to get individual values and compare them).
My problem starts here. A dynamic array might have a length of 1, 2, 3, 4, 5, 6 (depending on the select options on the page). I therefore can't do this as there won't always be two selects
for (i = 0; i < dynamicArr[0].length; i += 1) {
}
for (i = 0; i < dynamicArr[1].length; i += 1) {
}
How would I go about finding out the length and looping individually like the above e.g. if there are three selects, it will automatically know there are this many and loop through them like above.
If you are still confused, let me know.
Thanks.
Upvotes: 0
Views: 5968
Reputation: 559
you should try something like this:
dyn.forEach(function(el){//dyn is the dynamic array
console.log(el); //logs to console
});
Upvotes: 0
Reputation: 353
I hope I didn't get you wrong, but here's a solution:
for(i = 0; i < dynamicArr.length; i++) {
for(j = 0; j < dynamicArr[i].length; j++) {
// do something here..
}
}
Upvotes: 0
Reputation: 59232
You can always use Array.forEach
dynamicArr.forEach(function(el){
console.log(el);
});
Upvotes: 1