The aim of this puzzle: Complete the average()
function definition so that it returns the average value of the array
Walkthrough of the solution: The average (also called the “arithmetic mean”) of a set of numbers is calculated by adding all the numbers up and the dividing the total by the number of values used.
The function definition starts by creating a variable called total
. Since nothing has been added up yet, it starts at 0. Next, there’s a for...of
loop that goes through each element
of the array
. Inside that loop, the element
should be added to the total
using the +=
operator. Once the loop is done, the total
will be the sum of all the numbers in the array
. To return
the average, the total
should be divided by the number of values. The number of values is the .length
of the array
, so the return
value should be total / array.length
.
Sample code solution:
(Tap below to reveal)
import { getData, findHotels } from 'grasshopper.reviews';
import { getRatings } from 'myFunctions';
function average(array) {
let total = 0;
for (let element of array) {
total += element;
}
return total/array.length;
}
let grasslandRatings = getRatings(getData('Grassland', findHotels));
console.log(grasslandRatings);
console.log('The average is:');
console.log(average(grasslandRatings));
JavaScript Concepts: Arithmetic Operator (/), Assignment Operator (+=), Callback Functions, Calling Functions, Code Block (for loop, function), console.log()
, import
, .length
Additional Code (hidden code that runs before the puzzle’s code):
let _hotelReviews = [
{
type: 'Hopaday Inn',
city: 'Hopalot',
price: 138,
rating: 4.0
},
{
type: 'Hopaday Inn',
city: 'Hopalot',
price: 78,
rating: 3.8
},
{
type: 'Hopaday Inn',
city: 'Hoptropolis',
price: 86,
rating: 2.4
},
{
type: 'Hopaday Inn',
city: 'Hoptropolis',
price: 126,
rating: 4.4
},
{
type: 'Hopaday Inn',
city: 'Grassland',
price: 138,
rating: 3.0
},
{
type: 'Hopaday Inn',
city: 'Grassland',
price: 245,
rating: 4.6
},
{
type: 'The Grassy Suites',
city: 'Hopalot',
price: 189,
rating: 4.4
},
{
type: 'The Grassy Suites',
city: 'Hopalot',
price: 111,
rating: 2.4
},
{
type: 'The Grassy Suites',
city: 'Hoptropolis',
price: 171,
rating: 2.8
},
{
type: 'The Grassy Suites',
city: 'Hoptropolis',
price: 191,
rating: 2.8
},
{
type: 'The Grassy Suites',
city: 'Grassland',
price: 265,
rating: 4.1
},
{
type: 'The Grassy Suites',
city: 'Grassland',
price: 186,
rating: 3.5
},
{
type: 'Hopton Inn',
city: 'Hopalot',
price: 160,
rating: 2.4
},
{
type: 'Hopton Inn',
city: 'Hoptropolis',
price: 226,
rating: 4.5
},
{
type: 'Hopton Inn',
city: 'Hoptropolis',
price: 192,
rating: 3.5
},
{
type: 'Hopton Inn',
city: 'Grassland',
price: 149,
rating: 4.9
}
];
const getData = (city, afunction) => {
afunction(city.trim().charAt(0).toUpperCase() + city.trim().toLowerCase().slice(1));
};
const findHotels = city => {
_hotelReviews.filter( review => review.city === city);
};
const getRatings = hotelList => {
hotelList.map(hotel => hotel.rating)
};