Skip to main content
deckarduk
Inspiring
May 26, 2023
Question

InDesign JS arrays quesion...

  • May 26, 2023
  • 2 replies
  • 1052 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

Adobe 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 )

FRIdNGE
Inspiring
May 26, 2023

Hi Uwe,

 

Weird approach! …

 

var a =
[
	"a",
	"b",
	"c",
	"d",
	"e",
	"f",
    "g"
];

var resultArrayStartWithZero = [];

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

alert( "1/ " + resultArrayStartWithZero )

var resultArrayStartWithOne = [];

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

alert( "2/ " + resultArrayStartWithOne )

 

(^/)  The Jedi

deckarduk
deckardukAuthor
Inspiring
May 26, 2023

Variation:

 

var a =
[
	"a",
	"b",
	"c",
	"d",
	"e",
	"f",
    "g"
];

for ( var i = a.length-1; i >= 0; i=i-2 ) a.splice(i,1);

alert( "1/ " + a )

var a =
[
	"a",
	"b",
	"c",
	"d",
	"e",
	"f",
    "g"
];

for ( var i = a.length-2; i >= 0; i=i-2 ) a.splice(i,1);

alert( "2/ " + a )

 

(^/)


Nice!

Thanks for the posts and alternative solutions 🙂

Adobe 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

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.