reduce and sorting
JavaScript · Unit 5: Arrays
- Full plan
- JavaScript
- 10 exercises
reduce boils the whole array down to a single value. It takes two things: an arrow with the accumulator and the item, and the value the accumulator starts at.
const nums = [10, 20, 30];
const total = nums.reduce(
(sum, n) => sum + n,
0
);
console.log(total);Prints
60
The rest of the explanation is in the lesson, which is part of the full plan.
Exercises in this lesson
You do them in the app, which checks them on the spot and explains why.
1. Predict the output
What does this code print?
2. Complete the code
Complete it so the result is 24, the product of the three.
3. Multiple choice
What does this code do?
4. Predict the output
What does this code print?
5. Complete the code
Complete it to sort the points from highest to lowest.
6. Find the bug
This program should print the points from lowest to highest. Which line has the error?
7. Predict the output
What does this code print?
8. Predict the output
What does this code print?
9. Put the lines in order
Put in order the function that adds up the prices with
reduce.10. Predict the output
These are the points of four players. What does it print?
It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.