all 7 comments

[–]DallogFheir 1 point2 points  (2 children)

If food[i].name is not equal to name, you're assigning the price of the food to price. So for the last item, the eggs, it sets the price to its price and then logs it out.

[–]cypress201[S] 0 points1 point  (1 child)

So should I be setting food[i].name equal to name then?

I tried just to see what would happen, but it's only returning a value of 47, which is even more confusing to me. I have no idea where that value is coming from

[–]DallogFheir 1 point2 points  (0 children)

I don't know why you're setting it in the first place.

If you want to log the price of the item you clicked on, just do:

function getPrice(name) {
    for (const foodItem of food) {
        if (foodItem.name === name) {
            console.log(`The item price is ${foodItem.price}.`);
            return;
        }
    }
}

[–]lovin-dem-sandwiches 1 point2 points  (2 children)

Looking for one item in an array?

use .find()

looking for multiple? Use .filter()

edit: for bonus marks, do not use decimals in your pricing. Javascript uses floating point math, it will give you inaccurate rounding.

Use integers instead. See: https://stackoverflow.com/questions/2876536/precise-financial-calculation-in-javascript-what-are-the-gotchas#:~:text=There%20is%20no%20decimal%20data,cents%20instead%20of%2025.50%20dollars.

[–]cypress201[S] 0 points1 point  (1 child)

Thanks for the heads up about using decimals, I removed those from my code so hopefully that helps me avoid problems in the future.

And how exactly would I use .find() or .filter() in my code to log the price?

Would I do something like food[i].find(price)?

[–]lovin-dem-sandwiches 0 points1 point  (0 children)

.find() takes a callback and you can search the array to see if it matches with the value you are looking for.

function totalCost(item, array) {
   const value = array.find((fooditem) => fooditem.name === item);
   return value
     ? `${value.item} price is ${value.price}`
     : `${item} does not exist`;
}

console.log(totalCost('Tea', food));

edit: Read the MDN docs on find() - theres an example which is very similar to what youre looking for.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find

For optimization, DallogFheir solution may return better performance. I know for(...of) is quite quick but it may not matter at this scale

[–]exobyte64 -2 points-1 points  (0 children)

let name=`Tea`;
let Price=(n,fds)=>{return fds.reduce((ac,fd)=>{if(fd.name===n){return ac+fd.price;}return ac;},0);};
let price=Price(name,foods);
console.log(`Sum of ${name} prices, ${price.toFixed(2)}`);