Skip to main content
deckarduk
Inspiring
May 26, 2023
Question

InDesign JS arrays quesion...

  • May 26, 2023
  • 2 replies
  • 1071 views

Hi everyone,

Just a quick question about arrays...

Is there a quick way to pull out all the even numbered elements separately and the same for the odd numbered ones?

Or, is it a question of looping through the array with an increment of 2 ?

Thanks in advance.

This topic has been closed for replies.

2 replies

Community Expert
May 26, 2023

Hi @deckarduk ,

let's see:

"Looping the array with increments of 2 would be one solution."

 

Exactly this.

Examples:

var a =
[
	0 ,
	1 ,
	2 ,
	3 ,
	4,
	5

];

var resultArrayStartWithZero = [];

for( var n=0; n<a.length; n=n+2 )
{
	resultArrayStartWithZero[resultArrayStartWithZero.length++] = n ;
};

// Result: 0,2,4

resultArrayStartWithOne = [];

for( var n=1; n<a.length; n=n+2 )
{
	resultArrayStartWithOne[resultArrayStartWithOne.length++] = n ;
};

// Result: 1,3,5

 

Regards,
Uwe Laubender
( Adobe Community Expert )

deckarduk
deckardukAuthor
Inspiring
May 26, 2023

Hi Uwe,

Thanks for the post.

You've echoed the method I was going to use. A loop with an increment of 2 and changing the start point i.e. n=0 or n=1.

Thank you again for the help 🙂

Community Expert
May 26, 2023

I suppose whatever you do would involve a loop mostly, unless you join the array values into a string and do some Grep magic. Is running a loop troublesome in your case?

-Manan

-Manan
deckarduk
deckardukAuthor
Inspiring
May 26, 2023

Hi Manan,

Thanks for the reply. Interesting idea regarding using GREP.

I haven't tried the loop method yet, just thought I'd check in advance that I'm not missing a nice arrays method.

The array I'm dealing with will only have a few hundred items in it, nothing too big.

Thanks again.