0

I'm want to loop an array inside and array using JavaScript

outerArray = ["1","2","3","4","5","6","7","8","9","10"];
innerArray = ["val-1","val-2","val-3"];

so that the console logs out:

1,val-1
2,val-2
3,val-3
4,val-1
5,val-2
6,val-3
7,val-1
8,val-2
9,val-3
10,val-1

Using:

for (var i = 0; i < outerArray.length; i++) {
 console.log(i);
}

Obviously logs: 1,2,3,4,5,.....

However I cant use:

for (var i = 0; i < outerArray.length; i++) {
 console.log(i+','+innerArray[i]);
}

As this would give undefined after "val-3" as its a different length to the outer array.

Dave Chen
11k8 gold badges42 silver badges72 bronze badges
asked Sep 4, 2013 at 17:03
1
  • That's not an outer array, that's simply starting the loop over. Loop up the modulus operator. Commented Sep 4, 2013 at 17:05

2 Answers 2

3

You seem to want

console.log(outerArray[i]+','+innerArray[i%innerArray.length]);

Reference on the % operator

answered Sep 4, 2013 at 17:05
Sign up to request clarification or add additional context in comments.

4 Comments

@zaf that's why I added a link to the operator's description.
jsfiddle.net/Pzsyg - also, I think you meant console.log(outerArray[i]+','+... as the question is asked
@ToreHanssen Probably, yes.
@dystroy ah yes, that link on the mozilla developer network explains it all.
0
outerArray.forEach(function (elem, idx) {
 console.log(elem + ", " + innerArray[idx % innerArray.length]);
});

http://jsfiddle.net/bh4bs/

answered Sep 4, 2013 at 17:06

1 Comment

Let's precise that forEach isn't compatible with IE8 : developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.