Fix the Bug in Filtering Unique Usernames from an Array
The provided JavaScript function is supposed to return an array of unique usernames from a list of user objects. However, it currently returns duplicates. Your task is to debug and fix the code to ensure it returns only unique usernames.
Challenge prompt
You are given a function getUniqueUsernames that accepts an array of user objects, each having a 'username' property. The function is meant to return an array of unique usernames. However, the current implementation has a bug and returns duplicate usernames. Identify and fix the bug so that the function correctly returns an array with no duplicates.
Guidance
- • Examine how the existing code checks for duplicates and why it might be failing.
- • Consider using JavaScript data structures or methods better suited for uniqueness checks.
- • Test your function on inputs that have repeated usernames to ensure duplicates are removed.
Hints
- • Check how the indexOf method is used and if it properly detects duplicates.
- • Think about using a Set or an object to track seen usernames more effectively.
Starter code
function getUniqueUsernames(users) {
const unique = [];
users.forEach(function(user) {
if (unique.indexOf(user.username) !== -1) {
unique.push(user.username);
}
});
return unique;
}Expected output
getUniqueUsernames([{username: 'alice'}, {username: 'bob'}, {username: 'alice'}, {username: 'carol'}]) // ['alice', 'bob', 'carol']
Core concepts
Challenge a Friend
Send this duel to someone else and see if they can solve it.