0

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.

3 Answers 3

1

You can always use Array.forEach

dynamicArr.forEach(function(el){
   console.log(el);
});
Sign up to request clarification or add additional context in comments.

1 Comment

Would that give me both values at the same time so I can access both of them and compare? If so, could you give me an example?
0

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..
    }
}

1 Comment

Hey, Thanks for the response. I have already tried this method. That allows me to loop through the inner arrays :). I need to get them separate so that I can compare them.
0

you should try something like this: dyn.forEach(function(el){//dyn is the dynamic array console.log(el); //logs to console });

1 Comment

Can you expand on this and show me how I can compare both returned values. I can see how it works in the console, but don't know how I would use it just yet.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.