Arrays

Insert names to a sorted list
<!DOCTYPE html>

<!-- insert_names.html 
     A document for insert_names.js
     -->
<html lang = "en">
  <head> 
    <title> Name list </title>
    <meta charset = "utf-8" />
  </head>
  <body>
    <script type = "text/javascript"  src = "insert_names.js" >
    </script>
  </body>
</html>

// insert_names.js 
//   The script in this document has an array of
//   names, name_list, whose values are in 
//   alphabetic order. New names are input through
//   prompt. Each new name is inserted into the 
//   name array, after which the new list is 
//   displayed.

// The original list of names

      var name_list = new Array("Al", "Betty", "Kasper",
                         "Michael", "Roberto", "Zimbo");
      var new_name, index, last;

// Loop to get a new name and insert it

      while (new_name = 
                prompt("Please type a new name", "")) {

// Loop to find the place for the new name

        last = name_list.length - 1;
   
        while (last >= 0 && name_list[last] > new_name) { 
          name_list[last + 1] = name_list[last];
          last--;
        }

// Insert the new name into its spot in the array

        name_list[last + 1] = new_name;

// Display the new array

        document.write("<p><b>The new name list is:</b> ",
                       "<br />");
        for (index = 0; index < name_list.length; index++)
          document.write(name_list[index], "<br />");

/* There is another way to go over every element as below:
	for(a in name_list)
	  document.write(name_list[a], "<br />");
*/

        document.write("</p>");
      } //** end of the outer while loop

Two-dimensional array
<!DOCTYPE html>

<!-- nested_arrays.html 
     A document for nested_arrays.js
     -->
<html lang = "en">
  <head> 
    <title> Array of arrays </title>
    <meta charset = "utf-8" />
  </head>
  <body>
    <script type = "text/javascript"  src = "nested_arrays.js" >
    </script>
  </body>
</html>

// nested_arrays.js 
//   An example illustrate an array of arrays

// Create an array object with three arrays as its elements

      var nested_array = [[2, 4, 6],
                          [1, 3, 5],
                          [10, 20, 30]
                         ];

// Display the elements of nested_list

      for (var row = 0; row <= 2; row++) { 
        document.write("Row ", row, ":  ");

        for (var col = 0; col <=2; col++) 
          document.write(nested_array[row][col], " ");

        document.write("<br />");
      }