Unit 2B

by Larry Adams

JavaScript

console.clear();

// Array to hold Person Objects
var contacts = [];

// Contacts Object
function Person(fName, lName, street, city, state, zip, email) {
    this.fName = fName;
    this.lName = lName;
    this.street = street;
    this.city = city;
    this.state = state;
    this.zipCode = zip;
    this.email = email;
    this.getPerson = function() {
        return this.fName + " " + this.lName;
    }
}

// Function to add a Contacts Object to the Array
// No return
function addContacts(fName, lName, street, city, state, zip, email) {
    contacts.push(new Person(fName, lName, street, city, state, zip, email));
}

// Add People            
addContacts('John', 'Harvard', '110 Adams St', 'Cambridge', 'MA', 02138-3722, '[email protected]');
addContacts('Lawerence', 'Adams', '110 Harvard St', 'Cambridge', 'MA', 02138-3722, '[email protected]');
addContacts('Barbara', 'Smith', '110 Smith St', 'Cambridge', 'MA', 02138-3722, '[email protected]');

// function to find People in the Arrray   
// returns a new Array
function findPeople(lName) {
    var results = []
    var len = people.length;
    for (var i = 0; i < len; i++) {
        if (people[i].lName == lName) {
            results.push(people[i]);
        }
    }
    return results;
}

// function to display serach results
// no return
function displayPeople(peeps) {
    var len = peeps.length;
    for (var i = 0; i < len; i++) {
        console.log(peeps[i].getPerson());
    }
}

var results = findPeople('Smith');
if (results.length > 0) {
    displayPeople(results);
} else {
    console.log('No people found.');
}