Second Midterm Solutions

In all of the questions below you should assume that you are working with a JavaScript file that contains a global variable people that stores an array of objects. Each object has a name property that stores a string and an age property that stores an integer.

1. In the HTML file that goes with this JavaScript file we have the following elements:

<label for="name">Your name:</label>
<input type="text" id="name" /><br/>
<label for="age">Your age:</label>
<input type="text" id="age" /><br/>
<button id="add">Add Person</button>

Write the code for a function that you can use as an action function for the button. This function should create a new object using the data in the two text elements and add that object to the people array. (To convert text to a number in JavaScript you can use the code Number(text) where text is a variable containing text.)

function add() {
  let nameInput = document.getElementById('name');
  let ageInput = document.getElementById('age');
  let obj = {name:nameInput.value,age:Number(ageInput.value)};
  people.push(obj);
}

2. Write some JavaScript code that can filter the list of objects in the people array down to an array of objects where the age of the person is greater than or equal to 18. Use the filter() method to do this, and put the resulting array in a variable named adults.

adults = people.filter(p=>{return p.age >= 18;});

3. In the HTML file that goes with this JavaScript file we have the following elements:

<table>
  <thead>
    <tr>
      <th>Name</th>
      <th>Age</th>
    </tr>
  </thead>
  <tbody id="people">
  </tbody>
</table>

Write JavaScript code that puts all of the people in the people array in the body of this table.

let body = document.getElementById('people');
body.innerHTML = '';
let n = 0;
while(n < people.length) {
  let row = document.createElement('tr');
  row.innerHTML = '<td>'+people[n].name+'</td><td>'+
                  people.age+'</td>';
  body.appendChild(row);
  n++;
}

4. In the HTML file that goes with this JavaScript file we have the following elements.

<p>Average age is <span id="average">unknown</span>.</p>

Write JavaScript code that displays the average age of the people in the people array in the span.

let total = 0;
let n = 0;
while(n < people.length) {
  total = total + people[n].age;
  n++;
}
let avg = total/people.length;
let avgSpan = document.getElementById('average');
avgSpan.innerText = avg;