1

maybe this is a simple question, but i really confused with this loop.

I have 2 arrays like below:

var angkaPertama = [
    '0',
    '3',
    '8',
    '6',
    '1',
    '9',
    '5',
    '12',
    '14',
    '65',
    '54',
    '23'
]

var angkaKedua = [
    '0',
    '1',
    '2',
    '3'
]

How can i make a loop so the result is like below:

0            =>          0
3            =>          1
8            =>          2
6            =>          3

1            =>          0
9            =>          1
5            =>          2
12           =>          3

14           =>          0
65           =>          1
54           =>          2
23           =>          3

I am try this code, but fail

for (var i = 0; i < angkaPertama.length; i++) {
    for (var j = 0; j < angkaKedua.length; j++) {
        console.log(angkaPertama[i] + angkaKedua[j])
        if (i == 4) {
            break
        }
    }
}
3
  • for (var i = 0; i< 4 && i < angkaPertama.length; i++) { Commented Mar 30, 2016 at 11:47
  • Why don't you put them together? angkaPertama.concat(angkaKedua); Will give you 1 array. Commented Mar 30, 2016 at 11:48
  • Duplicate: stackoverflow.com/a/1584377/3378621 Commented Mar 30, 2016 at 11:51

4 Answers 4

6

Try to use a simple modulo math at this context,

angkaPertama.forEach(function(itm,i){
  console.log(itm + " => " + angkaKedua[i % (angkaKedua.length)]);
}); 

DEMO

Sign up to request clarification or add additional context in comments.

1 Comment

@MalhadiJr Glad to help! :)
0

Try this:

var j = 0;
for(var i = 0; i < angkaPertama.length; i++)
{
  if(j >= angkaKedua.length){ j = 0; } 
  console.log(angkaPertama[i] + ' => ' + angkaKedua[j]);
  j = j + 1;
}

Comments

0

Yes it is pretty easy when u use % (modulo):

var angkaPertama = [
  '0',
  '3',
  '8',
  '6',
  '1',
  '9',
  '5',
  '12',
  '14',
  '65',
  '54',
  '23'
]

var angkaKedua = [
  '0',
  '1',
  '2',
  '3'
]

angkaPertama.forEach(function(e,i) {
  document.write(e +" => "+angkaKedua[i%angkaKedua.length]+"<br>");
})

Comments

0
var j=0
for (var i = 0; i < angkaPertama.length; i++) {
    if(j==5)
    {
        j=0
    }
    console.log(angkaPertama[i] + angkaKedua[j++])
}

Comments

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.