LearnFrenzy
Sign in Take a free test

Destructuring · Destructuring Coding Problems · Question 2

A function that returns several statistics in JavaScript Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
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
main.js
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`);

Output Verified by running it on Node.js

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links