Array handling - basic questions

I have a list of ID numbers, which I want to store as an array i.e. [1,2,9,2,6], and then have a index number which cycles forward and gives me the Nth value (by index).

What’s the best approach for this?

I’m getting stuck at trying to establish the length of the array, using the count token, it’s just not working. I tried splitting the variable into multiple lines instead of being one-line comma delineated, and using the LINES calculation, still nothing. GPT + Grok are taking me down strange rabbit holes, and I’m struggling to find the right documentation on here.

Could someone point me in the right direction please?

thanks so much

p.s. ccstone’s response in this post shows part of what i’m trying to do, but my “key” is a dynamic number which cycles through the length of the array, from 0 to “array.length()”. How can i find out the array length?

https://forum.keyboardmaestro.com/t/arrays-and-arrays-and-arrays-and-somebody-please-help-me-arrays/25275/2

It works like this, simple example with a default (comma) delimiter below. Also note that Keyboard Maestro’s arrays are 1 base indexed, rather than 0.

3 Likes

oh wow, that’s a great little nugget, thank you Evan Honeyeater :wink:

What a strange method, I wonder why array[0] = length… but wonderful to know.

@Evan_Mangiamele's method is great if you want to grab the nth element of your array.

If you want to cycle through the array, doing something to each element in turn, you can use the "For Each" Action that splits your text into a Collection of substrings and loops through that Collection -- you can add an incrementing counter if you want one:

For Each a Pseudo.kmmacros (4.5 KB)

Image

Both methods let you set the string to use as the separator -- with the first you would put the string between the token's ] and the closing %, so to get the 2nd element of the variable Local_myArray that contained the text

cat==mySep==dog==mySep==fish

...you'd use

%Variable%Local_myArray[2]==mySep==%

And both methods fail if any of your elements contain the separator, so

1,2,"Hello, Bob!",4,5

will break. That's when you go back to your bracketed array notation and treat it as a JSON array -- note that KM's JSON arrays are also 1-indexed and 0 still gets you the length of the array:

For Each a JSON Array.kmmacros (3.7 KB)

Image

So, plenty of choices depending on your data and what you want to do.

1 Like

It was free, so I used it.

You can also do array[-2] to get the second last element.

5 Likes