I think there something wrong with the test , if you pass the test 1 , 2 and 5 you fail test 3 the same thing the other way round
Your code so far
// function getLaptopCost(laptops, budget) {
// const affordableLaptop = laptops
// .filter(price => price < budget)
// .sort((a,b) => b-a)
// console.log(affordableLaptop)
// if (affordableLaptop.length > 2) {
// if (affordableLaptop[0]) {}
// } else {
// return 0
// }
// }
function getLaptopCost(laptops, budget) {
// 1. Remove duplicates and sort the prices in descending order.
const uniqueSortedLaptops = [...new Set(laptops)].sort((a, b) => b - a);
// 2. Filter for laptops within the budget.
const affordableLaptops = uniqueSortedLaptops.filter(price => price <= budget);
// 3. Check and return based on the number of affordable laptops.
if (affordableLaptops.length >= 2) {
// If there are at least two affordable laptops, return the second most expensive.
console.log(affordableLaptops[1] && affordableLaptops[0])
return affordableLaptops[0] && affordableLaptops[1];
} else if (affordableLaptops.length === 1) {
// If there is exactly one affordable laptop, return its price.
return affordableLaptops[0];
} else {
// If no laptops are within the budget, return 0.
return 0;
}
}
getLaptopCost([1500, 2000, 1800, 1400], 1900)
getLaptopCost([2099, 1599, 1899, 1499], 2200)
getLaptopCost([1200, 1500, 1600, 1800, 1400, 2000], 1450)
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36
Note - please do not post code like that. The entire block of code should have a single set of backticks before it and a single set of backticks after it. Breaking up the lines like this makes it harder to read the code.
I was experiencing the same problem and emdes12 and efimberg22’s answers definitely helped me with passing all the tests as I was always struggling with test 3 (getLaptopCost([2099, 1599, 1899, 1499], 2200) should return 1899).
Either I passed all tests but failed no. 3 or just passed no. 3 and 4 and failed the rest.
Thinking of task 1 as “The second most expensive laptop if all laptops are within your budget, or[…]” and basically comparing the array length of the selected laptops with the given laptops length was the missing piece for me.