Our World Statistics Day conversations have been a great reminder of how much statistics can inform our lives. Do you have an example of how statistics has made a difference in your life? Share your story with the Community!
Choose Language Hide Translation Bar
Staff (Retired)

Looping through an Associative Array's elements


You need to look at every element in an Associative Array


use the <<First and <<Next messages

// load a table of elements
dt = Open( "https://en.wikipedia.org/wiki/List_of_chemical_elements", HTML Table( 4, Column Names( 2 ), Data Starts( 5 ) ) );
// make an associative array using "H" to lookup "Hydrogen" and some of its properties
map_Symbol_To_Data = Associative Array( dt[1 :: 118, "Symbol"], dt[1 :: 118, [3/*element name*/, 1/*element number*/, 7/*atomic weight*/]] );
// close the table
Close( dt, nosave );

// loop through the keys using <<FIRST and <<NEXT
For( sym = map_Symbol_To_Data << first, !Is Empty( sym ), sym = map_Symbol_To_Data << next( sym ),
	// print the symbol and look up the related data 
	Write( "\!n", sym, " ", map_Symbol_To_Data[sym] )

// another way to loop through them; this requires duplicating the data
keys = map_Symbol_To_Data << getkeys;
values = map_Symbol_To_Data << getvalues;
// loop through the pair of lists using an index
For( ikey = 1, ikey <= N Items( keys ), ikey += 1,
	sym = keys[ikey];
	Write( "\!n", sym, " ", values[ikey] );
	// also, you don't have to use a list of values, 
	// you could use the key to look it up:
	Write( "\!n", sym, " ", map_Symbol_To_Data[sym] );

The middle block above demonstrates the aa<<First and aa<<Next messages, and the IsEmpty test. Sending the aa<<First message to the associative array object returns the first key. The aa<<Next(prev key) returns the next key in the sequence.

The <<first, <<next technique can streamline the JSL a lot by not introducing unneeded variables. The third block introduces three extra variables and some copying. Creating the two lists may make sense if you need them anyway or will use them several times. The lookups in the associative array are slower than indexing into the list.

See Also




Clever use of a for loop.  I have only used  while's with associative arrays before.  I will have to try this.

Article Labels

    There are no labels assigned to this post.

Article Tags