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.

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

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/

1 Comment

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.