简体   繁体   中英

How to find a value in an array of objects using JavaScript?

I want to:

  1. Find the cheapest and most expensive food and drink.
  2. Find the id and name of drinks and foods if their price is higher than 10.

My attempt:

 let menu = [
            { id: 1,  name: "Soda",price: 3.12,size: "4oz",type: "Drink" },
            { id: 2, name: "Beer", price: 6.50, size: "8oz", type: "Drink" },
            { id: 3, name: "Margarita", price: 12.99, size: "12oz", type: "Drink" },
            { id: 4, name: "Pizza", price: 25.10, size: "60oz", type: "Food" },
            { id: 5, name: "Kebab", price: 31.48, size: "42oz", type: "Food" },
            { id: 6, name: "Berger", price: 23.83, size: "99oz", type: "Food" }
            ]

I would be happy and thankful if anybody could help.
Thanks in Advanced.

here is an example:

let menu = [
            { id: 1,  name: "Soda",price: 3.12,size: "4oz",type: "Drink" },
            { id: 2, name: "Beer", price: 6.50, size: "8oz", type: "Drink" },
            { id: 3, name: "Margarita", price: 12.99, size: "12oz", type: "Drink" },
            { id: 4, name: "Pizza", price: 25.10, size: "60oz", type: "Food" },
            { id: 5, name: "Kebab", price: 31.48, size: "42oz", type: "Food" },
            { id: 6, name: "Berger", price: 23.83, size: "99oz", type: "Food" }
        ];
        
function getCheapest(array) {
    return Math.min(...array.map(item => item.price));
}

function getExpensive(array) {
    return Math.max(...array.map(item => item.price));
}

function getFoodsAndDrinksMoreThan(array, minVal = 10){
        return array.filter(item => item.price > minVal).map(item => ({id: item.id, name: item.name}));
}

console.log(getCheapest(menu));

console.log(getExpensive(menu));

console.log(getFoodsAndDrinksMoreThan(menu));

The first one could be achieved with Array.prototype.reduce by comparing the first and second argument of the function you pass into it and returning the smaller one.

For 2. that sounds like a case for Array.prototype.filter to me.

Let me know if you need more guidance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM