Home > Enterprise >  How to filter the name in the console on the basis of city provided in the argument?
How to filter the name in the console on the basis of city provided in the argument?

Time:09-10

I have created a class named restaurant manager with an array named as 'restaurantList' . Inside this array I have passed name of restaurant with their address and city . After that I have created a function named as 'filterRestaurantByCity' in which I am trying to filter the restaurant name on the basis of the city provided in the argument.. THIS MY JAVASCRIPT CODE:-

enter code here class restaurantManager {
constructor() {
    this.restaurantList = [
        { name: "Barbeque Nation", address: "Phulwariya", city: "Varanasi" },
        { name: "The Table", address: "Cantt Station", city: "Bengluru" },
        { name: "i love my wife", address: "Lohamandi", city: "Pune" },
        { name: "Batti chokha", address: "Maldhiya", city: "Delhi" }
    ]
}
enter code here filterRestaurantByCity(Varanasi){
   let givencity = Varanasi
    let b = this.restaurantList.filter((item) => {return item.city==givencity})
    console.log(b.name)
}}


enter code here  let myobject = new restaurantManager()


enter code here  let c = myobject.filterRestaurantByCity()

After executing this code I am getting undefined in console. How to define it????????

CodePudding user response:

class restaurantManager {
constructor() {
    this.restaurantList = [
        { name: "Barbeque Nation", address: "Phulwariya", city: "Varanasi" },
        { name: "The Table", address: "Cantt Station", city: "Bengluru" },
        { name: "i love my wife", address: "Lohamandi", city: "Pune" },
        { name: "Batti chokha", address: "Maldhiya", city: "Delhi" }
    ]
}
filterRestaurantByCity(city){
   let givencity = city
    let b = this.restaurantList.filter((item) => {return item.city==givencity})
    return b;
}}

let myobject = new restaurantManager()
let c = myobject.filterRestaurantByCity("Varanasi");

console.log("Restaurants: ", c);

CodePudding user response:

Here 'b' returns an array, so b.name is returning undefined

let b = this.restaurantList.filter((item) => {
    return item.city == givencity
});

Solution:

You should return 'b' instead.

filterRestaurantByCity(Varanasi) {
    let givencity = Varanasi
    return this.restaurantList.filter((item) => {
        return item.city == givencity
    })
}

Now console.log(c) after let c = myobject.filterRestaurantByCity('Delhi')

  • Related