Refactor Messy JavaScript Array Processing Function
Clean up and improve the readability and efficiency of a JavaScript function that processes an array of user objects. The function currently contains redundant code, unclear variable names, and inefficient looping that you need to refactor without changing its output.
Challenge prompt
You are given a function that takes an array of user objects and returns an array of usernames for users who are active and over 18 years old. The existing code works correctly but is cluttered and inefficient. Refactor the function to make it more readable, concise, and performant without altering the output. Users array example: [ { username: 'alice', age: 22, isActive: true }, { username: 'bob', age: 17, isActive: true }, { username: 'carol', age: 19, isActive: false } ] Refactor the code provided in starterCode to achieve the same result in a cleaner way.
Guidance
- • Use array higher-order functions like filter and map to simplify the code.
- • Improve variable naming for clarity and follow JavaScript conventions.
- • Remove unnecessary variables and redundant checks.
Hints
- • Think about chaining array methods to avoid intermediate steps.
- • Avoid using traditional for loops when array methods can express the logic more declaratively.
- • Remember to keep the function's output unchanged after refactoring.
Starter code
function getActiveAdultUsernames(users) {
let result = [];
for (let i = 0; i < users.length; i++) {
let user = users[i];
if (user.isActive === true) {
if (user.age > 18) {
result.push(user.username);
}
}
}
return result;
}Expected output
getActiveAdultUsernames([{ username: 'alice', age: 22, isActive: true }, { username: 'bob', age: 17, isActive: true }, { username: 'carol', age: 19, isActive: false }]) // ['alice']
Core concepts
Challenge a Friend
Send this duel to someone else and see if they can solve it.