Associative array, for loop sorting keys ??

Get help with using AutoHotkey (v1.1 and older) and its commands and hotkeys
Bulgogi
Posts: 15
Joined: 01 Oct 2019, 12:30

Associative array, for loop sorting keys ??

06 Oct 2019, 14:41

Hello,
Is there a way to print the names in the order of insertion ?

IE :
- John
- Alex
- Peter

and not Alex, John, Peter which is what it currently does

Code: Select all

names := array()

names["John"]:=1
names["Alex"]:=2
names["Peter"]:=3

for key, val in names {
MsgBox % key " : " val

}
swagfag
Posts: 6222
Joined: 11 Jan 2017, 17:59

Re: Associative array, for loop sorting keys ??

06 Oct 2019, 15:02

assoc array is unordered(alphanumeric order actually). u can push assoc arrays into regular arrays or use the Scripting.Dictionary comobject
User avatar
boiler
Posts: 16925
Joined: 21 Dec 2014, 02:44

Re: Associative array, for loop sorting keys ??

06 Oct 2019, 16:28

If you're saying that you can count on the value that was assigned as being their insertion order, you could build another array that is basically swapping the keys and the values, then use that one. I'm not sure what purpose you'd be serving but this does it:

Code: Select all

names := array()
ordered := array()

names["John"]:=1
names["Alex"]:=2
names["Peter"]:=3

for key, val in names {
	ordered[val] := key
}

for key, val in ordered {
	MsgBox, % key " : " val
}

Return to “Ask for Help (v1)”

Who is online

Users browsing this forum: aitaixy, dipahk and 211 guests