Refactor a User Data Processing Function for Clarity and Performance
Improve the readability and efficiency of a JavaScript function that processes an array of user objects by removing duplicates, sorting them by age, and mapping to a simplified format.
Challenge prompt
You are given a function that processes an array of user objects. Each user object has id, name, and age properties. The function removes duplicates (based on id), sorts the users by age ascending, and then maps the users to an array that contains only their names and ages. Your task is to refactor the given function to improve its readability and performance while keeping the exact same output. Make sure to: - Remove redundant steps or loops, - Avoid unnecessary array iterations or mutations, - Use modern JavaScript features where appropriate, - Keep the function pure with no side effects.
Guidance
- • Use a Set or a Map to efficiently filter out duplicate users by id.
- • Try to minimize the number of iterations by combining operations where possible.
- • Use array destructuring and arrow functions for cleaner syntax.
Hints
- • Consider using Map to track users by their ids, which preserves insertion order and avoids duplicates.
- • Chaining methods like filter, sort, and map is clean but may be optimized by joining some steps.
Starter code
function processUsers(users) {
// Remove duplicates
const uniqueUsers = [];
for (let i = 0; i < users.length; i++) {
let isDuplicate = false;
for (let j = 0; j < uniqueUsers.length; j++) {
if (users[i].id === uniqueUsers[j].id) {
isDuplicate = true;
break;
}
}
if (!isDuplicate) uniqueUsers.push(users[i]);
}
// Sort by age
uniqueUsers.sort(function(a, b) {
return a.age - b.age;
});
// Map to simplified format
const result = [];
for (let i = 0; i < uniqueUsers.length; i++) {
result.push({ name: uniqueUsers[i].name, age: uniqueUsers[i].age });
}
return result;
}Expected output
[ { name: 'Alice', age: 25 }, { name: 'Bob', age: 30 }, { name: 'David', age: 40 } ]
Core concepts
Challenge a Friend
Send this duel to someone else and see if they can solve it.