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

Viewed 35

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..

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(Varanasi) {
        let givencity = Varanasi
        let b = this.restaurantList.filter((item) => {
            return item.city == givencity
        })
        console.log(b.name)
    }
}

let myobject = new restaurantManager()

let c = myobject.filterRestaurantByCity()

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

2 Answers

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')

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);
Related