raineorshine
8/3/2013 - 6:43 PM

5 beginner examples of loops and arrays.

5 beginner examples of loops and arrays.

// #2: Find out if all the names in a list are less than 10 characters. (Store true or
// false in a variable to indicate the final result)
var names = ["John", "Dave", "James Fenimore Cooper", "Sarah", "Gene", "Alexandria"];
var result = true;

for(var i=0; i<names.length; i++) {
    if(names[i].length >= 10) {
        result = false;
        break; // special statement that immediately ends the loop
    }
    // result is already true, so this would be unnecessary
    //else {
    //    result = true;
    //}
}

console.log(result);
// #4: Find all of the names in a list that are less than 10 characters and insert them
// into an output array (leaving out the names that are 10 or more characters)
var names = ["John", "Dave", "James Fenimore Cooper", "Sarah", "Gene", "Alexandria"];
var output = [];

for(var i=0; i<names.length; i++) {
    if (names[i].length<10) {
        output.push(names[i]); 
    }
}

console.log(output);
// #5: Ordinalize a list of numbers
// An exercise for the reader!
// #3: Pluralize a list of nouns. Insert the plural version into an output array.
var animals = ["dog", "cat", "horse"];
var output = [];

for(var i=0; i<animals.length; i++) { 
    var plural= animals[i] + "s"; 
    output.push(plural); 
}

console.log(output); 
// #1: Square a list of numbers
var numbers = [10, 2, 3, 4, 5];
var output = [];

// loop through each number in the array
for(var i=0; i<numbers.length; i++) {

    // multiply each number by itself
    var product = numbers[i] * numbers[i];
    
    // take the squared number, and insert it into the output array
    output.push(product);
}  

console.log(output);