0

I'm trying to compare the name to the item names in the list and return the price of that item but it's not going through the full list. Can someone explain to me what I'm doing wrong and how to correct it?

let items = [
  {
    itemName: "Effective Programming Habits",
    type: "book",
    price: 13.99
  },
  {
    itemName: "Creation 3005",
    type: "computer",
    price: 299.99
  },
  {
    itemName: "Finding Your Center",
    type: "book",
    price: 15.00
  }

]function priceLookup (itemsList, name) {
  let price = null;
  for (item of itemsList) {
    if (item.itemName === name) {
      price = item.price;
    }
    else { price = "No item found with that name";
    }
  }
  return price;
}
Z_Cason
  • 25
  • 5
  • 1
    Please provide a [mre], which should include a sample of data that is in `itemsList` and a value for `name`, so that we can recreate the issue. You can use [Stack Snippets](https://meta.stackoverflow.com/q/358992/215552) (icon looks like `<>`) to provide that. – Heretic Monkey Jun 15 '20 at 19:49
  • Learn about `Array.find()` – epascarello Jun 15 '20 at 19:50
  • Instead of initially setting `price = null`, set this to the not found text, and use `break` as pointed out – Keith Jun 15 '20 at 19:51
  • Does this answer your question? [Find object by id in an array of JavaScript objects](https://stackoverflow.com/questions/7364150/find-object-by-id-in-an-array-of-javascript-objects) – Heretic Monkey Jun 15 '20 at 19:52

2 Answers2

2

It is going through the full list, and that's the problem. Notice that if the if branch is hit, price gets populated, but the next time around in the loop, the else branch may take place, so price will be overwritten with that string.

You can use break to stop looping in your if branch once you've found the match, or use the find method of the Array instead.

function priceLookup (itemsList, name) {
  const price = itemsList.find(item => item.itemName === name);
  return price ?? "No item found with that name";
}
Jacob
  • 77,566
  • 24
  • 149
  • 228
1

It's happening because you have reassigned price in else to ""No item found with that name". Possible Solution:

function priceLookup (itemsList, name) {
  let price = "No item found with that name";
  for (item of itemsList) {
    if (item.itemName === name) {
      price = item.price;
      break;
    }
  }
  return price;
}
Shivanshu Gupta
  • 324
  • 2
  • 9