javascriptintermediate10 minutes
Fix the Bug in Array Filtering and Object Mapping Function
Identify and fix the bug in a JavaScript function designed to filter an array of user objects and map them to a list of their names based on age criteria.
Challenge prompt
The provided JavaScript function filterAndExtractNames is intended to take an array of user objects and return an array of names of users whose age is 18 or older. However, the function currently returns incorrect or unexpected output. Your task is to debug and fix the code so it behaves as specified.
Guidance
- • Check how the array is filtered by age and ensure the condition is correct.
- • Verify the method used to extract names after filtering is properly applied on the filtered array.
Hints
- • Verify the filtering condition uses the correct comparison operator (>=).
- • Ensure the map function is used on the filtered result rather than the original array.
Starter code
function filterAndExtractNames(users) {
return users.map(user => user.name).filter(user => user.age >= 18);
}
// Example input
const users = [
{ name: 'Alice', age: 17 },
{ name: 'Bob', age: 22 },
{ name: 'Charlie', age: 18 },
{ name: 'David', age: 15 }
];
console.log(filterAndExtractNames(users));Expected output
[ 'Bob', 'Charlie' ]
Core concepts
array filteringarray mappingcallback functionsconditional logic
Challenge a Friend
Send this duel to someone else and see if they can solve it.