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

I want to:
Find the cheapest and most expensive food and drink.
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.

Related

Question from a beginner: Unexpected JS behavior [duplicate]

I'm trying to convert an array of objects where i return duplicated objects if the object properties quantity is greater than 1.
const objects = [
{ id: 1, name: "Scissor", price: 2, quantity: 3 },
{ id: 2, name: "Hat", price: 6.5, quantity: 1 },
{ id: 3, name: "Socks", price: 0.5, quantity: 5 },
];
// desired return
[
{ id: 1, name: "Scissor", price: 2 }
{ id: 1, name: "Scissor", price: 2 }
{ id: 1, name: "Scissor", price: 2 }
{ id: 2, name: "Hat", price: 6.5}
{ id: 3, name: "Socks", price: 0.5 }
{ id: 3, name: "Socks", price: 0.5 }
{ id: 3, name: "Socks", price: 0.5 }
{ id: 3, name: "Socks", price: 0.5 }
{ id: 3, name: "Socks", price: 0.5 }
]
My code:
const objects = [
{ id: 1, name: "Scissor", price: 2, quantity: 3 },
{ id: 2, name: "Hat", price: 6.5, quantity: 1 },
{ id: 3, name: "Socks", price: 0.5, quantity: 5 },
];
let newObjects= [];
Object.entries(objects).forEach(([key, value]) => {
for (let i=0; i < value.quantity; i++){
newObjects.push({ id: value.id, name: value.name, price: value.price})
}
});
console.log(newObjects);
So my code above does work, does return what i wanted, however i feel like there is a better/smoother and more of ES6 and beyond method. Could anyone please suggest a better way?
You could use .fill() and .flatMap().
const objects = [
{ id: 1, name: "Scissor", price: 2, quantity: 3 },
{ id: 2, name: "Hat", price: 6.5, quantity: 1 },
{ id: 3, name: "Socks", price: 0.5, quantity: 5 },
];
let newObjects = objects.flatMap(e=>
Array(e.quantity).fill({id: e.id, name: e.name, price: e.price})
);
console.log(newObjects);
You can use an array reduce along with an array fill.
The map is required only if you want to have unique references otherwise you can fill using the same object.
const objects = [
{ id: 1, name: "Scissor", price: 2, quantity: 3 },
{ id: 2, name: "Hat", price: 6.5, quantity: 1 },
{ id: 3, name: "Socks", price: 0.5, quantity: 5 },
];
const output = objects.reduce((a, c) => {
return a.concat(Array(c.quantity).fill({}).map(x=>({
id: c.id,
name: c.name,
price: c.price
})))
}, []);
console.log(output)

How to create a nested array of object from an array of objects

How Can I loop through this array of objects and change it so that the individual menu items are nested in the object menu_name?
const menus = [
{ menu_name: 'Entre', id:0 },
{
name: 'Soup',
price: 14.99,
id:1
},
{
name: 'Chips & Salsa',
price: 7.99,
id:2
},
{
name: 'Chicken Nuggets',
price: 12.99,
id:3
},
{ menu_name: 'Sides', id:4 },
{
name: 'Fries',
price: 4.99,
id:5
},
{
name: 'Drinks',
price: 2.99,
id:6
},
{
name: 'Onion Rings',
price: 5.99,
id:7
},
];
the end result should look like this for each menu_name object, where an array of menus is nested in the menu_name object
{
menu_name: 'Sides',
menu: [
{
name: 'Fries',
price: 4.99,
},
{
name: 'Drinks',
price: 2.99,
},
{
name: 'Onion Rings',
price: 5.99,
},
],
},
You can easily achieve this using reduce and object destructuring
const menus = [
{ menu_name: "Entre", id: 0 },
{
name: "Soup",
price: 14.99,
id: 1,
},
{
name: "Chips & Salsa",
price: 7.99,
id: 2,
},
{
name: "Chicken Nuggets",
price: 12.99,
id: 3,
},
{ menu_name: "Sides", id: 4 },
{
name: "Fries",
price: 4.99,
id: 5,
},
{
name: "Drinks",
price: 2.99,
id: 6,
},
{
name: "Onion Rings",
price: 5.99,
id: 7,
},
];
const result = menus.reduce((acc, curr) => {
const { menu_name } = curr;
if (menu_name) {
acc.push({ menu_name, menu: [] });
} else {
const { name, price } = curr;
acc[acc.length - 1].menu.push({ name, price });
}
return acc;
}, []);
console.log(result);
var newMenu = [];
menus.forEach(menu=>{
if(menu.menu_name){
newMenu.push({...menu, menu: []})
}else{
newMenu[newMenu.length-1].menu.push(menu)
}
});

Code is not executed when filtering the array to display the desired value

I want to show the name and price of foods whose price is higher than 10 in the console, but I will encounter an error.
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" },
];
const maxPriceFood = () => {
for (let value of menu) {
for (let value of menu.price)
if (value > 10 && type === "Food") {
return `name food : ${menu.name} price food : ${menu.price}`
}
}
};
console.log(maxPriceFood());
menu.price is not iterable (unlike menu which is an array).
You can refactor the method to work like this:
for (let menuItem of menu) {
if (menuItem.price > 10 && menuItem.type === "Food") {
return `name food : ${menuItem.name} price food : ${menuItem.price}`
}
}
Another simpler option is to use the array built in functions for that: (filter and forEach).
const maxPriceFood = () => menu.filter(menuItem => menuItem.price > 10 &&
menuItem.type === "Food").forEach(x => console.log(`name food : ${x.name} price food : ${x.price}`));
maxPriceFood();
//"name food : Pizza price food : 25.1"
//"name food : Kebab price food : 31.48"
//"name food : Berger price food : 23.83"
You can use Array.filter and Array.map to get and show food items with a price over 10:
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" },
];
const maxPriceFood = () => {
// Get items with a price over 10
const itemsOver10 = menu.filter(item => item.price > 10 && item.type === "Food");
return itemsOver10.map(item => `name food : ${item.name} price food : ${item.price}`);
};
console.log(maxPriceFood());
You're doing an extra loop.
In my example, the first loop declares in the variable "entry" each one of the instances in the list, and compares their price.
Also, if you do a return, you exit the function without checking the rest of the prices.
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" },
];
const maxPriceFood = () => {
let maxPrices = [];
for (let entry of menu) {
if (entry.price > 10 && entry.type === "Food") {
maxPrices.push(`name food : ${entry.name} price food : ${entry.price}`);
}
}
return maxPrices;
};
console.log(maxPriceFood());

Filter the desired items in the array and display them

I want to use the array methods to find the cheapest food in the menu and display the foods whose price is higher than 10 along with the name and ID in the console. Thank you for your help.
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" },
];
It's not very complex, just read the array with a FOR loop and filter the data with an IF .. :)
var 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" },
];
var menu2 = []; // creates a new array to hold the results
for(var i = 0; menu[i]; i++){
if(menu[i].price > 10) menu2[menu2.length] = menu[i]; // If an item has a price greater than 10 then I copy it to the new menu
}
console.log(menu2); // Display the new menu with the filtered data in the console

Trying to filter an array of products with an array of filters upon click

I want to filter a list of products depending on the selected filters by the user. For example:
Here is the list of products:
const products = [
{
id: 1,
productName: 'Strawberry Basil',
productImgURL:
'https://cdn.shopify.com/s/files/1/0274/3641/7123/products/Cherry_Pop_Still_4K_Front-CherryPop.png?v=1588713373',
type: ['berry', 'citrusy', 'fancy'],
price: 5.5,
},
{
id: 2,
productName: 'Sour Blueberry',
productImgURL:
'https://cdn.shopify.com/s/files/1/0274/3641/7123/products/SourBlueBerry_Still_4K_Front-SourBlueberry.png?v=1588713584',
type: ['sour', 'berry'],
price: 4,
},
{
id: 3,
productName: 'Blackberry Jam',
productImgURL:
'https://cdn.shopify.com/s/files/1/0274/3641/7123/products/BlackBerry_Jam_Still_4K_Front-BlackberryJam.png?v=1595035965',
type: ['berry'],
price: 10,
},
{
id: 4,
productName: 'Orange Nectarine',
productImgURL:
'https://cdn.shopify.com/s/files/1/0274/3641/7123/products/Orange_Nectarine_Still_4K_Front-OrangeNectarine.png?v=1588713522',
type: ['citrus', 'fancy', 'juicy'],
price: 6,
},
{
id: 5,
productName: 'Lemon Verbena',
productImgURL:
'https://cdn.shopify.com/s/files/1/0274/3641/7123/products/Lemon_Verbena_Still_4K_Front-LemonVerbena.png?v=1588713474',
type: ['citrus', 'classic', 'floral'],
price: 4.5,
},
{
id: 6,
productName: 'Extra Peach',
productImgURL:
'https://cdn.shopify.com/s/files/1/0274/3641/7123/products/ExtraPeach_Still_4K_Front-ExtraPeach.png?v=1588713411',
type: ['juicy'],
price: 8.5,
}
]
I'm grouping the filters upon user's click like this:
const filtered = ['classy', 'berries', 'juicy']
How can I filter the product list to show all those products that have this type in their types of array property? So if the user clicks on one then it will filter one and so on.
We can use Array.filter, Array.some and Array.includes to find the products that match the filtered Array.
For each product we check if the product.type array and filtered array overlap:
const products = [ { id: 1, productName: 'Strawberry Basil', productImgURL: 'https://cdn.shopify.com/s/files/1/0274/3641/7123/products/Cherry_Pop_Still_4K_Front-CherryPop.png?v=1588713373', type: ['berry', 'citrusy', 'fancy'], price: 5.5, }, { id: 2, productName: 'Sour Blueberry', productImgURL: 'https://cdn.shopify.com/s/files/1/0274/3641/7123/products/SourBlueBerry_Still_4K_Front-SourBlueberry.png?v=1588713584', type: ['sour', 'berry'], price: 4, }, { id: 3, productName: 'Blackberry Jam', productImgURL: 'https://cdn.shopify.com/s/files/1/0274/3641/7123/products/BlackBerry_Jam_Still_4K_Front-BlackberryJam.png?v=1595035965', type: ['berry'], price: 10, }, { id: 4, productName: 'Orange Nectarine', productImgURL: 'https://cdn.shopify.com/s/files/1/0274/3641/7123/products/Orange_Nectarine_Still_4K_Front-OrangeNectarine.png?v=1588713522', type: ['citrus', 'fancy', 'juicy'], price: 6, }, { id: 5, productName: 'Lemon Verbena', productImgURL: 'https://cdn.shopify.com/s/files/1/0274/3641/7123/products/Lemon_Verbena_Still_4K_Front-LemonVerbena.png?v=1588713474', type: ['citrus', 'classic', 'floral'], price: 4.5, }, { id: 6, productName: 'Extra Peach', productImgURL: 'https://cdn.shopify.com/s/files/1/0274/3641/7123/products/ExtraPeach_Still_4K_Front-ExtraPeach.png?v=1588713411', type: ['juicy'], price: 8.5, } ]
const filtered = ['classy', 'berries', 'juicy'];
const results = products.filter(product => {
return product.type.some(productType => filtered.includes(productType))
})
console.log(`Matching products (${results.length}):`, results.map( ({ productName }) => productName));

Categories