0

I wanted the food with the lowest price to be displayed on the console, but my code does not work. Thank you for helping me get the correct code.

Give me the output I want : name : Berger price : 23.83

let menu = [
    { id: 1, name: "Soda", price: 3.12, size: "4oz", type: "Drink" },
    { id: 2, name: "Beer", price: 6.50, size: "8oz", type: "Drink" },
    { id: 3, name: "Margarita", price: 12.99, size: "12oz", type: "Drink" },
    { id: 4, name: "Pizza", price: 25.10, size: "60oz", type: "Food" },
    { id: 5, name: "Kebab", price: 31.48, size: "42oz", type: "Food" },
    { id: 6, name: "Berger", price: 23.83, size: "99oz", type: "Food" },
];

const cheap_food = () => {
    const cheap = menu.filter(menuItem => menuItem.price > 0 && menuItem.type === "Food");
    cheap.forEach(price => console.log(Math.min(price)));
}
cheap_food();
0

2 Answers 2

2

Destructure the price from each menuItem object that you're getting. Even after filter, the cheap array is an array of objects and not just price values. With your updated question, following will work :-

let menu = [
    { id: 1, name: "Soda", price: 3.12, size: "4oz", type: "Drink" },
    { id: 2, name: "Beer", price: 6.50, size: "8oz", type: "Drink" },
    { id: 3, name: "Margarita", price: 12.99, size: "12oz", type: "Drink" },
    { id: 4, name: "Pizza", price: 25.10, size: "60oz", type: "Food" },
    { id: 5, name: "Kebab", price: 31.48, size: "42oz", type: "Food" },
    { id: 6, name: "Berger", price: 23.83, size: "99oz", type: "Food" },
];


const cheap_food = () => {
    const cheap = menu.filter(menuItem => menuItem.price > 0 && menuItem.type === "Food");
        const item = cheap.sort((itemA,itemB)=>itemA.price-itemB.price)[0];
        console.log(`${item.name} price : ${item.price}`);
}
cheap_food();

Sign up to request clarification or add additional context in comments.

6 Comments

This is not my answer My desired result name : Berger price : 23.83
@Amir7222 Seems you updated your question.
Yes, please help me to reach a conclusion
@Amir7222 The above can be done with .forEach as well. It's just .sort seemed cleaner to me.
const item = cheap.sort((itemA,itemB)=>itemA.price-itemB.price)[cheap.length-1]. Our sort implementation returns an array where elements are sorted in increasing order. So first element (index = 0) is smallest and last element (index = length of array - 1) is the greatest.
|
0

Just use price.price instead of only price. The reason for that is that the filter function returns the filtered object. Therefore you need to wether destructure your object or access the price directly.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.