Search code examples
javascriptarraysfunctionobjectreturn

When using a function and for loop how do I return the first matching value in an object if there are duplicates or similar values?


For example, say I have the following duplicates in my dataset and I input name = Finding Your Center as an argument into the below function. I want to return the price of the first matching itemName. Instead of returning 15.00 because 15.00 is the first value that matches the string argument, the above function would return 1500 because it's looping through the entire object data instead of stopping at the first matching/similar value.

 let duplicates = [
      {
        itemName: "Finding Your Center",
        type: "book",
        price: 15.00
      },
      {
        itemName: "Finding Your Center",
        type: "book",
        price: 1500.00
      }];

Here's my pseudocode and my function so far. This function returns all the values I need expect for using a specific data set.

// Create priceLookUp function to find price of a single item
// Give the function two paramenters: an array of items and an item name as string
// priceLookUp = undefined for nomatching name
// loop through the items array checking if name = itemName
// return the price of item name matching string
// for a matching/similar value the code should stop running at the first value instead of going through the rest of the loop

function priceLookup (items, name){
  let priceOfItem = undefined;
  for (let i = 0; i < items.length; i++) 
  if (name === items[i].itemName) 
  {priceOfItem = items[i].price;}
  return priceOfItem;
}

How would I get the function as written using a for loop to stop running at the first matching value and not loop through the entire array?


Solution

  • function priceLookup (items, search) {
      let priceOfItem = [];
      for (let i = 0; i < items.length; i++) 
      if (search === items[i].itemName)
        {priceOfItem.push(items[i].price);}
        return priceOfItem[0];
     }
      

    For this function, it makes more sense to me to create an empty array to hold the new return value. Since we only want to return the first match, it would make sense to return the first value in the array. By returning priceOfItem[0], it returns the first value in the array if there are multiple values that meet the if condition.