javascriptintermediate10 minutes
Refactor a Function to Improve Array Filtering and Mapping Logic
Refactor the provided JavaScript function to improve readability, reduce complexity, and maintain the same output when filtering and mapping an array of user objects.
Challenge prompt
The function below filters an array of user objects to include only those users who are active and older than a certain age. It then maps the filtered users to a new array containing only the id and name properties. Refactor the code to make it cleaner and more readable while preserving the exact output behavior.
Guidance
- • Focus on improving the readability and maintainability of the code without changing its functionality.
- • Consider breaking down complex expressions or chaining for clarity.
- • Ensure the function returns the exact same output for the same input.
Hints
- • Use descriptive variable names for intermediate results if necessary.
- • Consider using array methods like filter and map separately rather than inline chaining.
- • Avoid redundant checks or unnecessary comments.
Starter code
function getActiveUserSummaries(users, minAge) {
return users.filter(function(user) {
return user.active === true && user.age > minAge;
}).map(function(user) {
return {id: user.id, name: user.name};
});
}Expected output
[ { id: 1, name: 'Alice' }, { id: 3, name: 'Charlie' } ]
Core concepts
array filteringarray mappingcode readabilityfunction refactoring
Challenge a Friend
Send this duel to someone else and see if they can solve it.