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

Ways to recycle the table feature in angular2?

I am new to Angular2 framework and I am looking to efficiently reuse a single table component across my entire application. However, I am encountering challenges when it comes to displaying arrays in the table rows. How can I iterate through any type of ar ...

Displaying a Div element containing dynamically calculated values based on selected options in Angular

As a newcomer to Angular, I decided to challenge myself by building a simple app. Currently, my select options only display the keys of a data object. What I really want to achieve is to show a value beneath the second select box for each team, which displ ...

Error message: Unexpected token "(" in the asynchronous aspect of Meteor

Currently running meteor version 1.5.1, I am facing a bug while attempting to import an npm module (kraken-api) on the server side: import KrakenClient from 'kraken-api'; > W20170726-22:02:48.177(2)? (STDERR) packages/modules.js:677 ...

Display the size of the data array in VueJS once the data has been retrieved from the API

Using Vue JS, I have been attempting to retrieve data from an API. My goal is to determine the length of the array and then log it to the console using a method. However, every time I try to do this, the value logged is always "0" instead of the actual le ...

Automatically assigning a FormData key/value pair upon clicking using Puppeteer in NodeJS

While working on a NodeJS project, I am using Puppeteer to fill out a form. So far, the regular type and click functions work perfectly. After clicking the "submit" button, a POST request is sent to the server with some form data. I want to add a key/value ...

Unable to locate the JavaScript files within the NextJs and ReactJs project

I've encountered an issue when trying to import js files (which are libraries) in my project. I am currently using NextJS version 14.1.3 and ReactJS version 18.2.0. You can find the path to these files here Here is a glimpse of the project structure ...

Need to update various form fields at once with jquery?

There is a form with fields for firstname, lastname, email, country, along with edit icon and submit/cancel buttons. When the user clicks on the edit icon in the top right corner, all values will be displayed in textboxes and the country will be shown in ...

Is it possible to test the JEST configuration for the node_modules even when it is turned

I'm currently integrating Jest tests into an existing codebase, but I've encountered an error that's giving me some trouble. Jest came across an unexpected token Typically, this means you're trying to import a file that Jest can& ...

"PHP Are You Dealing with Excessive Whitespace

Currently, I am utilizing AJAX to handle the processing of my ChangePassword class, which is an extension of my DataProcessor class. For some reason, every data I receive from the AJAX response seems to have an added whitespace before it, almost like it&ap ...

Vue table does not update when checkbox is unchecked

I am currently utilizing Daisy UI and basic VUE to create a checkbox functionality. When I check the checkbox, it successfully filters the table entries; however, when I uncheck or check another checkbox, the filter does not refresh again. Below is my tab ...

How can I transfer a particular data value from a div to JavaScript within Laravel 5.0?

Displaying separate square divs based on integers retrieved from the database. This is the front-end view. I want to pass the room ID (code) to a JavaScript function when clicking on these div elements. https://i.stack.imgur.com/aIYTr.png Below is my cur ...

Why is the result of this specific JavaScript code a string?

let x = 2, y = x = typeof y; console.log(x); // >> 'string' Could you explain why the value of x ends up being a string in this code snippet? ...

The `mouseenter` event handler fails to trigger properly on its initial invocation

As I work on a function to remove a CSS class display:hidden; when the mouse enters a specific part of the DOM to reveal a menu, I encounter an issue. Upon loading the page and hovering over the designated area for the first time, the event fails to trigge ...

Discover the Mongoose Document and Arrange in a Random Order with Various Levels?

I am currently using a .find() method to sort documents in a collection based on their "status" and ordering them by most recent. Is it possible to first sort by status, and then randomly sort within each tier? For example, I have users divided into three ...

Is there a method to avoid redeclaring variables in JavaScript with jQuery?

In the structure of my code, I have the following setup. <!-- first.tpl --> <script> $(document).ready(function() { objIns.loadNames = '{$names|json_encode}'; } ) </script> {include file="second.tpl"} <! ...

I am interested in using an image upload box that includes a hidden input field. However, I have encountered issues with the functionality when the input field is hidden. Does anyone have any suggestions on how

I have limited experience and need some assistance with resolving this particular issue. I am looking to create an image upload box that works when clicked on the input field. Thank you in advance. function readURL(input) { if (input.files && ...

Encountering a hiccup during the installation process of Angular CLI

I'm encountering an issue in the command line, seeking assistance C:\Users\admin>npm -v 6.9.0 C:\Users\admin>npm install -g @angular/cli npm ERR! Unexpected end of JSON input while parsing near '...vkit/core":"8.0.4", ...

How to Prevent Scrolling When Modal is in Use on Full Page JS

I am trying to achieve the functionality where when the modal is open, I want to prevent full-page scrolling in JavaScript. The issue arises when I open the modal and try to scroll, it ends up moving the content that's behind the modal, which is actua ...

Node JS does not receive a response from JQuery Ajax

I have developed a form on the client side which includes: <html> <body> <script> $(document).ready(function() { $.ajax({ url: "Search.html", type: "POST", dataType : "json", s ...

Leveraging npm in vanilla JavaScript applications

Because of limitations set by the governance of my current project, I am unable to utilize many of the modern JS libraries and frameworks. Therefore, for our MVP, we are resorting to using vanilla JS directly loaded to the client (un-minified), which is no ...