JavaScript
Challenge - Array operations
Compute total revenue from a store's sales list with arrays, loops and reduce.
Sales list challenge
In this challenge you will compute the total revenue from a store's sales list. Each sale is an object: {product, price, quantity}.
You can find the total in two ways: walk the list with a for loop and add each sale, or fold it in one line with reduce. Both keep an accumulator variable.
You will use reduce here. The accumulator is sum with a starting value of 0. At each step you add price * quantity to sum.
Finding the total with reduce
reduce folds an array into a single value. It takes two parameters: a callback and a starting value.
The callback runs for each element and receives two arguments: sum (the value built so far) and sale (the current element). The callback returns the new sum.
For the sales list you return sum + sale.price * sale.quantity at each step. With a starting value of 0, the first sale sees sum as zero and the result accumulates correctly.
Exercise Write the totalRevenue function
Define a function named totalRevenue. It should take a sales parameter that is an array of sale objects; each sale has the shape {product, price, quantity}. Use reduce to sum price * quantity for every sale. Pass 0 as the starting value and return the total.
Show example solution
Inside totalRevenue call sales.reduce. The callback takes sum and sale; return sum + sale.price * sale.quantity. The second argument is 0.
Example solution:
function totalRevenue(sales) {
return sales.reduce(function (sum, sale) {
return sum + sale.price * sale.quantity;
}, 0);
}
Test yourself
-
Add to the accumulator with for...of
let total = 0;
for (const sale of sales) {
total ____= sale.price * sale.quantity;
}
Show answer
let total = 0;
for (const sale of sales) {
total +== sale.price * sale.quantity;
}
-
What does the second parameter of reduce determine?
sales.reduce(callback, 0);
- The length of the array
- The starting value of the accumulator
- Skips the first element
- The return type of the callback
Show answer
The starting value of the accumulator — Correct. The second parameter is the initial value of the accumulator; without it the first element is used.
Next lesson: Challenge - Object management