javascriptintermediate10 minutes

Refactor Nested Loops and Conditionals into Clean Functional Code

Improve the readability and maintainability of a JavaScript function that calculates a summary from an array of user objects with nested loops and conditionals, by refactoring it using higher-order array methods and cleaner logic without changing its behavior.

Challenge prompt

You are given a JavaScript function that calculates the total active users and their average age from an array of user objects. The current implementation uses nested loops and multiple conditionals making it hard to read and maintain. Refactor this function to achieve the same result using cleaner and more functional programming approaches such as array methods (map, filter, reduce), and reduce nesting where possible. Ensure that the output remains unchanged.

Guidance

  • Avoid nested loops and deep conditionals by using filter and reduce appropriately.
  • Use descriptive variable names and break down complex expressions for better readability.

Hints

  • Try chaining array methods like filter followed by reduce instead of explicit loops.
  • Calculate sums and counts inside a single reduce pass instead of multiple iterations.

Starter code

function summarizeUsers(users) {
  let activeCount = 0;
  let totalAge = 0;
  for (let i = 0; i < users.length; i++) {
    if (users[i].isActive) {
      activeCount++;
      totalAge += users[i].age;
    }
  }
  let averageAge = 0;
  if (activeCount > 0) {
    averageAge = totalAge / activeCount;
  }
  return { activeCount, averageAge };
}

Expected output

{ activeCount: 3, averageAge: 29.333333333333332 } // when input users: [ {age: 24, isActive: true}, {age: 30, isActive: false}, {age: 35, isActive: true}, {age: 29, isActive: true} ]

Core concepts

Array methodsFunctional programmingCode readabilityRefactoring

Challenge a Friend

Send this duel to someone else and see if they can solve it.