javascriptintermediate10 minutes

Refactor Messy Array Processing Function for Clarity and Efficiency

Improve the readability, efficiency, and overall code quality of a JavaScript function that processes arrays without changing its behavior.

Challenge prompt

You are given a JavaScript function that takes an array of user objects and returns an array of usernames in uppercase, but the original function is messy and inefficient. Refactor the function to improve readability and performance without changing its output or behavior.

Guidance

  • Focus on simplifying nested loops and conditional checks.
  • Use array methods such as map and filter to make the code more declarative.
  • Keep the function output and behavior exactly the same.

Hints

  • Consider using chaining of array methods to avoid intermediate variables.
  • Avoid using unnecessary temporary arrays or variables.
  • Make use of modern ES6+ syntax like arrow functions.

Starter code

function getUppercaseUsernames(users) {
  let result = [];
  for (let i = 0; i < users.length; i++) {
    if (users[i] && users[i].name) {
      let name = users[i].name;
      let upperName = "";
      for (let j = 0; j < name.length; j++) {
        upperName += name[j].toUpperCase();
      }
      result.push(upperName);
    }
  }
  return result;
}

Expected output

For input [{name: 'alice'}, {name: 'Bob'}, {name: 'charlie'}], the function returns ['ALICE', 'BOB', 'CHARLIE']

Core concepts

array methodsrefactoringcode readabilityES6 features

Challenge a Friend

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