Skip to main content
dublove
Legend
Jul 28, 2025 4:50 AM UTC
Answered

How to find even numbers in cp[i]?

var cp = pp.marginPreferences.columnsPositions;

I now want to distinguish between odd and even numbers.
cp[1], cp[3], cp[5]
cp[2], cp[4], cp[6]
I previously used cp[2*i] to represent even numbers and cp[2*i-1] to represent odd numbers, but in practice, as the numbers grow larger, the logic becomes confusing.
For example, when i=11, 2*i becomes 22, which is no longer near 11.

 

I think the correct logic should be:
Odd number + 1 = Even number.

m1b
m1bCorrect answer
Community Expert
Jul 28, 2025 5:06 AM UTC

@dublove you would use remainder operator (%). Something like this:

var doc = app.activeDocument;
var cp = doc.pages[0].marginPreferences.columnsPositions;
var even = [];
var odd = [];

for (var i = 0; i < cp.length; i++) {
    if (0 === i % 2)
        even.push(cp[i]);
    else 
        odd.push(cp[i]);
}

- Mark 

4 replies

m1b
Community Expert
m1bCommunity ExpertCorrect answer
Community Expert
Jul 28, 2025 5:06 AM UTC

@dublove you would use remainder operator (%). Something like this:

var doc = app.activeDocument;
var cp = doc.pages[0].marginPreferences.columnsPositions;
var even = [];
var odd = [];

for (var i = 0; i < cp.length; i++) {
    if (0 === i % 2)
        even.push(cp[i]);
    else 
        odd.push(cp[i]);
}

- Mark 

Translate
dublove
dubloveAuthor
Legend
Jul 28, 2025 6:34 AM UTC

Hi m1b,

It should be even.push(i);

I thought it could be done directly like this:
ev=even(i);

I understand now, thank you very much.

 

 

Translate
m1b
Community Expert
Community Expert
Jul 28, 2025 7:17 AM UTC

Yes `even` and `odd` in my example are Arrays, and push is a method to add something to the end of the array. So my example will put items 0,2,4,6,8 etc into even and items 1,3,5,7,9 etc into odd. Rememer that the first index of an array is 0, not 1.

Translate