Programming Fundamentals/Array Examples JavaScript

From Wikibooks, open books for an open world
Jump to navigation Jump to search

Arrays[edit]

// This program demonstrates array processing, including:
// display, total, max, min, parallel arrays, sort
// multidimensional arrays, and dynamic arrays.

main()

function main() {
   var names = ['Lisa', 'Michael', 'Ashley', 'Jacob', 'Emily'];
   var ages = [49, 48, 26, 19, 16];

   displayArray(names);
   displayArray(ages);

   var total = sum(ages);
   var maximum = max(ages);
   var minimum = min(ages);

   output('total: ' + total);
   output('maximum: ' + maximum);
   output('minimum: ' + minimum);

   displayParallel(names, ages);

   ages.sort();
   displayArray(ages);

   displayMultidimensional();
   dynamicArray();
}

function displayArray(array) {
   for (var index = 0; index < array.length; index++) {
       output('array[' + index + '] = ' + array[index]);
   }
}

function sum(array) {
   var total = 0;
   for (var index = 0; index < array.length; index++) {
       total += array[index];
   }
   return total;
}

function max(array) {
   var maximum = array[0];
   for (var index = 1; index < array.length; index++) {
       if (maximum < array[index]) {
           maximum = array[index];
       }
   }
   return maximum;
}

function min(array) {
   var minimum = array[0];
   for (var index = 1; index < array.length; index++) { 
       if (minimum > array[index]) {
           minimum = array[index];
       }
   }
   return minimum;
}

function displayParallel(names, ages) {
   for (var index = 0; index < names.length; index++) {
       output(names[index] + ' is ' + ages[index] + ' years old');
   }
}

function displayMultidimensional() {
   var game = [
       ['X', 'O', 'X'], 
       ['O', 'O', 'O'], 
       ['X', 'O', 'X'] ];

   for (var row = 0; row < 3; row++) {
       var line = '';
       for (var column = 0; column < 3; column++) {
           line += game[row][column];
           if (column < 2) {
               line += ' | ';
           }
       }
       output(line);
   }
}

function dynamicArray() {
   var array = []

   for (var index = 0; index < 5; index++) {
       var number = Math.floor(Math.random() * 100);
       array.push(number);
   }
   displayArray(array);
}

function output(text) {
  if (typeof document === 'object') {
    document.write(text);
  } 
  else if (typeof console === 'object') {
    console.log(text);
  } 
  else {
    print(text);
  }
}

Output[edit]

array[0] = Lisa
array[1] = Michael
array[2] = Ashley
array[3] = Jacob
array[4] = Emily
array[0] = 49
array[1] = 48
array[2] = 26
array[3] = 19
array[4] = 16
total: 158
maximum: 49
minimum: 16
Lisa is 49 years old
Michael is 48 years old
Ashley is 26 years old
Jacob is 19 years old
Emily is 16 years old
array[0] = 16
array[1] = 19
array[2] = 26
array[3] = 48
array[4] = 49
X | O | X
O | O | O
X | O | X
array[0] = 30
array[1] = 97
array[2] = 87
array[3] = 42
array[4] = 40

References[edit]