Question 2
Back to Exercise
Write stats(numbers) that returns the minimum, maximum, mean and count as an object, and destructure only the values you need in two different calls.
Solution
function stats(numbers) {
const count = numbers.length;
const sum = numbers.reduce((a, b) => a + b, 0);
return { min: Math.min(...numbers), max: Math.max(...numbers), mean: +(sum / count).toFixed(2), count };
}
const marks = [72, 88, 95, 61, 79];
const { min, max } = stats(marks);
const { mean: average, count } = stats(marks);
console.log(`Range ${min}–${max}, average ${average} over ${count} tests`);
Range 61–95, average 79 over 5 tests
Returning an object lets each caller pick fields by name in any order (and rename them, like mean: average) without caring about positions.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!