0

I need to write a function, priceLookup(items, itemName) then return the price for the item that is called. If there are no items that match the name passed in, the function should return undefined and if there is more than one item in the array that matches the name, the function should return the price of the first one that matches.

Example output:

priceLookup(items, "Effective Programming Habits") //=> 13.99

Given array:

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
  }
]

What I have so far:

function priceLookup(items, itemName) {
  if (items.length === 0) return undefined;
  
  for (let i = 0; i < items.length; i++) {
    let result = items.filter(price => items.price);
    return result;
  }
} 

I thought I could use the filter() method to return the price as each name was called however, this returns an empty array. (I'm sure I did it wrong)

1 Answer 1

3

Since you want to find the first match, if it exists, you should use .find, not .filter - and you don't need a for loop in addition to the array method. You're also supposed to return the price of the found object, not the whole object.

function priceLookup(items, itemName) {
  const found = items.find(item => item.itemName === itemName);
  if (found) return found.price;
}

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(items, itemName) {
  const found = items.find(item => item.itemName === itemName);
  if (found) return found.price;
}
console.log(priceLookup(items, "Effective Programming Habits"));

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.