2

so I have an array in which I store values in pairs. I can't use an object because keys may repeat so I use an array instead.

This is how the array may look:

array = ['id1', 'id5', 'id9', 'id12', 'id2', 'id9', 'id1', 'id4'];

So I want to iterate through it and get all the pairs, so I can use them for another function:

var a = 'id1';
var b = 'id5';    
doStuffWithThePair(a, b);

var a = 'id9';
var b = 'id12';    
doStuffWithThePair(a, b);

var a = 'id2';
var b = 'id9';    
doStuffWithThePair(a, b);

var a = 'id1';
var b = 'id4';    
doStuffWithThePair(a, b);

I tried with for loops, using if(i%2 == 0) but it doesn't work. How can I make this? Thanks in advance!

2
  • 3
    What about that: for (var i = 0; i < array.length - 1; i=i+2) { doStuffWithThePair(array[i], array[i+1]) } ? Commented Jul 15, 2016 at 6:39
  • Realized that right after I submitted the question, if you want feel free answer it to I can mark it as correct for other to see it in the future! Commented Jul 15, 2016 at 6:42

2 Answers 2

5

You can iterate through your array like this:

function doStuffWithThePair(a, b) {
    // your code is here.
    console.log(a, b);
}

var array = ['id1', 'id5', 'id9', 'id12', 'id2', 'id9', 'id1', 'id4'];
for (var i = 0; i < array.length - 1; i += 2) { 
    doStuffWithThePair(array[i], array[i + 1]);
}

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

Comments

1

function doStuffWithThePair (x, y) {
  console.log("x: " + x + ", y: " + y);
}

var a = ['id1', 'id5', 'id9', 'id12', 'id2', 'id9', 'id1', 'id4'];
for (var i = 0; i < a.length - 1; i+=2) { 
  doStuffWithThePair(a[i], a[i+1]);
}

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.