Refactor Nested Loops and Conditionals into Cleaner JavaScript Function
Improve the readability and maintainability of a JavaScript function that processes an array of user objects by refactoring nested loops and conditionals 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 for users who are active and have purchased at least one item costing over $20. The original function uses nested loops and multiple conditionals making it hard to read and maintain. Refactor the function to improve code clarity, reduce nesting, and utilize modern JavaScript methods like filter, some, and map while preserving the original functionality.
Guidance
- • Use Array.prototype.filter() to reduce nested if conditions where appropriate.
- • Replace inner loops that check purchases with Array.prototype.some() for better readability.
- • Use meaningful variable names and simplify return statements.
Hints
- • Instead of manually looping through purchases, consider if some purchase object meets the price criterion.
- • Filtering users first and then mapping to extract usernames can clean up the logic.
Starter code
function getEligibleUsernames(users) {
const result = [];
for (let i = 0; i < users.length; i++) {
if (users[i].isActive) {
let hasExpensivePurchase = false;
for (let j = 0; j < users[i].purchases.length; j++) {
if (users[i].purchases[j].price > 20) {
hasExpensivePurchase = true;
break;
}
}
if (hasExpensivePurchase) {
result.push(users[i].username);
}
}
}
return result;
}Expected output
For the input: [ { username: 'alice', isActive: true, purchases: [{price: 10}, {price: 30}] }, { username: 'bob', isActive: false, purchases: [{price: 50}] }, { username: 'charlie', isActive: true, purchases: [{price: 15}] } ] The output should be: ['alice']
Core concepts
Challenge a Friend
Send this duel to someone else and see if they can solve it.