javascriptintermediate10 minutes
Fix the Array Filtering Bug to Return Unique Even Numbers
A function meant to filter even numbers from an array and remove duplicates is currently returning incorrect results. Debug the code to ensure it returns only unique even numbers in ascending order.
Challenge prompt
You are given a function getUniqueEvenNumbers that takes an array of integers and is expected to return an array of unique even numbers sorted in ascending order. However, the provided code currently has bugs that prevent it from functioning correctly. Your task is to fix the bugs so that the function returns the correct output. For example, input [1, 2, 2, 3, 4, 4, 5, 6] should return [2, 4, 6].
Guidance
- • Check how the function filters even numbers and removes duplicates.
- • Ensure the output array only contains unique even numbers sorted in ascending order.
Hints
- • Remember that Array.filter is helpful for filtering based on conditions.
- • Use a Set or similar approach to remove duplicates from an array.
- • Make sure sort is applied correctly to numbers (not as strings).
Starter code
function getUniqueEvenNumbers(arr) {
// Filter even numbers
const evens = arr.filter(num => num % 2 === 0);
// Remove duplicates
const uniqueEvens = evens.filter((num, index) => evens.indexOf(num) === index);
// Sort numbers ascending (bug: sorting as strings)
uniqueEvens.sort();
return uniqueEvens;
}
// Example usage:
console.log(getUniqueEvenNumbers([1, 2, 2, 3, 4, 4, 5, 6]));Expected output
[2, 4, 6]
Core concepts
array filteringremoving duplicatessorting arraysdebugging
Challenge a Friend
Send this duel to someone else and see if they can solve it.