Browsing through items within arrays to evaluate their values

I am facing an issue with two arrays that consist of objects. The first array contains restaurant objects with attributes such as name and averagePrice, while the second array has price objects (cheap, medium, expensive) with properties like label, lowEnd, and highEnd to determine pricing categories. My goal is to develop a function that iterates through the restaurants and returns the one whose average price falls within a specified price range. However, I encountered an error message:

Cannot read properties of undefined (reading: lowEnd)

This error occurs because I am not accurately targeting the array object property for the price. Can anyone assist me in identifying the correct method to target an array object property? Thank you.

Below is the code snippet provided:

    const priceArray = [
    cheap = {label: '$', lowEnd: 10, highEnd: 20},
    medium = {label: '$$', lowEnd: 21, highEnd: 30},
    expensive = {label: '$$$', lowEnd: 31, highEnd: 40},

];


const restaurants = [
    McDonalds = {name: 'Mcdonalds', averagePrice: 12},
    Sushi = {name: 'Sushi', averagePrice: 25},
    Steak = {name: 'Steak', averagePrice: 35}
];




function showRestaurants(price) {
    for (let restaurant of restaurants) {
    //if the average price is cheap, log that restaurant
            if (restaurant.averagePrice >= priceArray.price.lowEnd && restaurant.averagePrice < priceArray.price.highEnd)
                console.log(restaurant);
        }
};

showRestaurants(medium);

Answer №1

You are missing the priceArray.price, but keep in mind that priceArray is an array with keys such as cheap, medium, and expensive.

Since you have already specified medium as the data to be checked, it would be advisable to use the price parameter in the function showRestaurants(price). In this way, medium will be considered as the price.

showRestaurants(medium);

A potential solution could involve:

  • Changing priceArray.price.lowEnd to price.lowEnd
  • Changing priceArray.price.highEnd to price.highEnd

const priceArray = [
  cheap = {
    label: '$',
    lowEnd: 10,
    highEnd: 20
  },
  medium = {
    label: '$$',
    lowEnd: 21,
    highEnd: 30
  },
  expensive = {
    label: '$$$',
    lowEnd: 31,
    highEnd: 40
  },

];


const restaurants = [
  McDonalds = {
    name: 'Mcdonalds',
    averagePrice: 12
  },
  Sushi = {
    name: 'Sushi',
    averagePrice: 25
  },
  Steak = {
    name: 'Steak',
    averagePrice: 35
  }
];




function showRestaurants(price) {
  for (let restaurant of restaurants) {
    //if the average price is cheap, log that restaurant
    if (restaurant.averagePrice >= price.lowEnd && restaurant.averagePrice < price.highEnd)
      console.log(restaurant);
  }
};

showRestaurants(medium);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

One way to achieve this would be by using the following code snippet:

 const priceArray = [
    {label: '$', lowEnd: 10, highEnd: 20},
    {label: '$$', lowEnd: 21, highEnd: 30},
    {label: '$$$', lowEnd: 31, highEnd: 40},

];


const restaurants = [
     {name: 'Mcdonalds', averagePrice: 12},
   {name: 'Sushi', averagePrice: 25},
   {name: 'Steak', averagePrice: 35}
];

const withPriceLabel  =  restaurants.map(r => {
 return {
   ...r,
   priceEvaluation: priceArray.find(p => r.averagePrice >= p.lowEnd && r.averagePrice <= p.highEnd).label
 }
})

console.log(withPriceLabel.filter(r => r.priceEvaluation === '$'))

Answer №3

Hey there, Nick! Let me provide you with a speedy solution:

const AFFORDABLE = { label: "$", lowEnd: 10, highEnd: 20 };
const MODERATE = { label: "$$", lowEnd: 21, highEnd: 30 };
const LUXURIOUS = { label: "$$$", lowEnd: 31, highEnd: 40 };

const priceRanges = [AFFORDABLE, MODERATE, LUXURIOUS];

const McDonalds = { name: "Mcdonalds", averagePrice: 12 };
const Sushi = { name: "Sushi", averagePrice: 25 };
const Steak = { name: "Steak", averagePrice: 35 };

const restaurants = [McDonalds, Sushi, Steak];

function displayRestaurants(price) {
  const filteredRestaurants = [];

  // Filtering by price category
  const categories = priceRanges.filter((level) => {
    return level.lowEnd < price && price < level.highEnd;
  });

  // Filtering the restaurants
  restaurants.map((restaurant) => {
    categories.map((category) => {
      if (
        category.lowEnd < restaurant.averagePrice &&
        restaurant.averagePrice < category.highEnd
      ) {
        filteredRestaurants.push(restaurant);
      }
    });
  });

  filteredRestaurants.map((restaurant) => console.log(restaurant.name));
}

displayRestaurants(15);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to retrieve the outcome of a node-sqlite3 query beyond the scope of db.get()?

I'm attempting to validate whether the sha256 hash stored in my sqlite database corresponds with the sha256 hash of the password that the user transmitted to my NodeJS server. The Auth() method is meant to deliver either a true or false result. Is the ...

Conflicting styles arise when using the makeStyles function from Material UI with imported

In working on a React component library using create-react-library, I have incorporated basic components that utilize Material UI components and the material UI hook-based styles pattern. For example (in a simplified form): // LibraryComponent.js const u ...

Swap out the default URL in components with the global constant

Could anyone offer some assistance with this task I have at hand: Let's imagine we have a global constant 'env' that I need to use to replace template URLs in components during build time. Each component has a default template URL, but for ...

What is the best way to dynamically change the content of a div based on user selection?

When a user selects an option in the HTML, I want to display another div set to Block. I tried putting the OpenAskuser() function in a button, but it didn't work either. It would be ideal if we could achieve this without a button. Just have the displ ...

Swapping out a class or method throughout an entire TypeScript project

Currently, I am working on a software project built with TypeScript. This project relies on several third-party libraries that are imported through the package.json file. One such library includes a utility class, utilized by other classes within the same ...

Testing the local transmission of form data via Javascript: A Step-by-Step guide

Currently studying how to send forms using JavaScript by manually creating an XMLHttpRequest. Towards the end of the provided example, there's a note: Note: If you want to send data to a third party website, keep in mind that this use of XMLHttpRequ ...

I encountered an issue while attempting to manipulate/retrieve the JSON value using REGEX, resulting in an undefined return

I am attempting to retrieve the currency value from a JSON file and if it is USD, then I want to change it to AUD. When trying to find the currency attribute in the JSON file, it returned 'undefined' as shown below: Code: var datastring = JSON. ...

Setting up webpack for React to utilize multiple entry points and outputs

Having some trouble configuring the server to handle multiple entries and outputs. The application utilizes Zurb Foundation, jQuery, and React. I'm aiming to exclude jQuery and foundation from the bundle.js file, while also creating a separate bundle ...

Tips for integrating CKEditor into an Angular 4 project

To start using CKEditor, I first installed it by running the command npm install ng2-ckeditor. Next, I included ckeditor.js in my index.html file. I then imported { CKEditorModule } from 'ng2-ckeditor'; in my app.module.ts file. After setup, I ...

Output JSON data from PHP for use in Javascript

Is there a way to effectively convert JSON data from PHP/Laravel into JSON for JavaScript? I have the JSON string from PHP, but it is only rendering as a string. How can I convert it to a JSON object in JavaScript? Take a look at my code below. $('#e ...

Check for a rapid return if the function ends up returning null in JavaScript

Is there a way to make this code more concise? const result = getResult(); if (!result) { return; } // Work with result I have several instances of this code in my project and I'm looking for a simpler solution like: const result = getResult() ...

Implementing a post request triggered by a button click in Node.js with Express

How can I invoke a controller from a button click event? I tested it in Postman and it works fine, but I'm having trouble calling it from a button on my front-end. I am using Nodemailer and Node Express to send emails. Here is my code. Can someone p ...

Next.js experiences slowdown when initializing props on the server side

I've been working on implementing SSR with Next.js. In my code, I'm fetching JSON data and using them as initial props. Everything works fine in development mode, but when I deploy to the server, fetching only works on the client-side (when navi ...

Guide on integrating buefy (a vue.js component library) into your Laravel blade template

I'm currently integrating buefy into my project, but I'm encountering issues with using vue.js on Laravel 5.8. Can anyone offer assistance? Here is the code snippet from my app.js: require('./bootstrap'); window.Vue = require('v ...

Create a custom overlay for an image that is centered horizontally and does not have a fixed width

I'm working with this HTML setup: <div class="container"> <img class="image" /> <div class="overlay"> <div class="insides">more content here</div> </div> &l ...

Troubleshooting my CSS navigation bar - What am I missing?

I've been developing a navigation bar using a combination of HTML, CSS, and JavaScript. After writing the code and setting the display of the bar to fixed, I encountered an issue where the content of the page was overlapping the nav bar. Below you&ap ...

Tips for including multiple JSON results into a single text box for auto-complete purposes

I am trying to combine different autocomplete list results into one text box. It's straightforward to use separate text boxes for different autocomplete results. HTML: <input id="university" name="university" type="text" /> <input id="unive ...

Ways to modify an object similar to manipulating an array collection

Hey there, I've heard that iterating and editing objects (not arrays) is not the best practice. Is there a more efficient way to do it as easily as it can be done with an array of objects? Check out this link for reference new Vue({ el: '#app ...

What is the best way to integrate PHP scripts into jQuery?

I need help integrating PHP into my jQuery sample. Specifically, I would like to insert a PHP variable ($sample) into the "var para1" in the code below. var storyIndictor = jQuery(_storyIndictors[position]); var _content = jQ ...

Click the button to access the provided link

I need to add a link for redirection to some buttons. Here is an example of the button code: <Tooltip title="Open New Ticket"> <IconButton aria-label="filter list"> <AddTwoToneIcon /> </IconButton> </T ...