Choose Language Hide Translation Bar
Staff (Retired)

## Looping through an Associative Array's elements

Problem

You need to look at every element in an Associative Array

Solution

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] );
);``````
Discussion

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.