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

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

Related

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

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

How to find a value in an array of objects using 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.

How do I get the total sum of nested arrays in Reactjs?

I want to get the total price of nested arrays in a specific category e.g: Hot Drinks.
Here is a sample of what I have now, so I want to filter out and get the total price of Hot Drinks Category only.
[
{
totalPrice: 30,
_id: '6014fa4324e125599eaa72b5',
orderItems: [
{
_id: '6014fa4324e125599eaa747ss',
category: 'Breakfast',
name: 'food name 1',
price: 3,
qty: 1,
},
{
_id: '6014fa4324e125599eaa747s5',
category: 'Hot Drinks',
name: 'drink name 1',
price: 3,
qty: 5,
},
{
_id: '6014fa4324e125599eaa74767',
category: 'Hot Drinks',
name: 'drink name 2',
price: 4,
qty: 2,
},
],
},
{
totalPrice: 23,
_id: '6014fa4324e125599eaa7276e',
orderItems: [
{
_id: '6014fa4324e125599eaa747ss',
category: 'Hot Drinks',
name: 'drink name 1',
price: 3,
qty: 6,
},
],
},
]
You can apply a filter method on the array and then just add the values on the filtered array. Something like below:
let prod = [
{
totalPrice: 30,
_id: '6014fa4324e125599eaa72b5',
orderItems: [
{
_id: '6014fa4324e125599eaa747ss',
category: 'Breakfast',
name: 'food name 1',
price: 3,
qty: 1,
},
{
_id: '6014fa4324e125599eaa747s5',
category: 'Hot Drinks',
name: 'drink name 1',
price: 3,
qty: 5,
},
{
_id: '6014fa4324e125599eaa74767',
category: 'Hot Drinks',
name: 'drink name 2',
price: 4,
qty: 2,
},
],
},
{
totalPrice: 23,
_id: '6014fa4324e125599eaa7276e',
orderItems: [
{
_id: '6014fa4324e125599eaa747ss',
category: 'Hot Drinks',
name: 'drink name 1',
price: 3,
qty: 6,
},
],
},
];
function getPriceByCategory(category, products) {
let price = 0;
products.forEach(orders => {
orders.orderItems.filter(order => order.category == category).forEach(item => {
price += item.price;
});
});
return price;
}
const totalPrice = getPriceByCategory('Hot Drinks', prod);
alert(totalPrice);
Sample JS Fiddle: https://jsfiddle.net/sagarag05/qwzju53f/9/
const filterBy = 'Hot Drinks';
const items = [
{
totalPrice: 30,
_id: '6014fa4324e125599eaa72b5',
orderItems: [
{
_id: '6014fa4324e125599eaa747ss',
category: 'Breakfast',
name: 'food name 1',
price: 3,
qty: 1,
},
{
_id: '6014fa4324e125599eaa747s5',
category: 'Hot Drinks',
name: 'drink name 1',
price: 3,
qty: 5,
},
{
_id: '6014fa4324e125599eaa74767',
category: 'Hot Drinks',
name: 'drink name 2',
price: 4,
qty: 2,
},
],
},
{
totalPrice: 23,
_id: '6014fa4324e125599eaa7276e',
orderItems: [
{
_id: '6014fa4324e125599eaa747ss',
category: 'Hot Drinks',
name: 'drink name 1',
price: 3,
qty: 6,
},
],
},
]
const sumOf = (items, filterBy) => {
let totalPrice = 0;
items.forEach(item => {
item.orderItems.forEach(orderItem => {
if (orderItem.category === filterBy) {
totalPrice += orderItem.price;
}
})
})
return totalPrice;
}
console.log(sumOf(items, filterBy))
let sum = 0;
allOrders.forEach(order => {
order.orderItems.forEach(item => {
if(item.category=='Hot Drinks') {
sum+ = item.price * item.qty
}});
});
sum has the total price for Hot Drinks
Assuming you named that information as data:
Generate a big array of all the "orderItems"
For each of those elements sum the price if the category is "Hot Drinks"
const totalPrice = data
.reduce((acc, { orderItems }) => [...acc, ...orderItems], [])
.reduce((acc, { category, price }) => category === "Hot Drinks" ? acc + price : acc, 0);
console.log(totalPrice); // 10
Use flatMap and reduce or alternatively using forEach and destructuring
const total = (arr, text) =>
arr
.flatMap(({ orderItems }) => orderItems)
.reduce((acc, { category, price }) =>
(acc + (category === text ? price : 0)), 0);
// alternatively
const total2 = (arr, text, acc = 0) => {
arr.forEach(({ orderItems }) =>
orderItems.forEach(
({ category, price }) => (category === text && (acc += price))
)
);
return acc;
};
const data = [
{
totalPrice: 30,
_id: "6014fa4324e125599eaa72b5",
orderItems: [
{
_id: "6014fa4324e125599eaa747ss",
category: "Breakfast",
name: "food name 1",
price: 3,
qty: 1,
},
{
_id: "6014fa4324e125599eaa747s5",
category: "Hot Drinks",
name: "drink name 1",
price: 3,
qty: 5,
},
{
_id: "6014fa4324e125599eaa74767",
category: "Hot Drinks",
name: "drink name 2",
price: 4,
qty: 2,
},
],
},
{
totalPrice: 23,
_id: "6014fa4324e125599eaa7276e",
orderItems: [
{
_id: "6014fa4324e125599eaa747ss",
category: "Hot Drinks",
name: "drink name 1",
price: 3,
qty: 6,
},
],
},
];
console.log(total(data, 'Hot Drinks'))
console.log(total2(data, 'Hot Drinks'))

ES6: Populate object value with a value from another object when ID is present

I would like to populate the value 'discount' for a product with the discount ID value from the array discounts, if the respective product ID exists as a value in the Discounts object.
const products = [{
id: "05cdb75d-7984-4dbf-b0f4-d6532163b66d",
name: "SANTO - Schnürstiefelette",
price: 199.95,
discount: 0,
},
{
id: "1b9b6c7e-c856-464c-ba64-98c9dd6733b5",
name: "AIR FORCE 1 07 LV8 - Sneaker low",
price: 109.95,
discount: 0,
},
{
id: "f831aaf4-347a-458f-bb0c-21cf02aeac2e",
name: "DUFF 9.0 - Sporttasche",
price: 34.95,
discount: 0,
},
{
id: "471ad894-150b-4a2b-881c-a9a4dbc4b401",
name: "Strickpullover",
price: 20.99,
discount: 0,
},
];
const discounts = [{
id: "5791ae04-a704-4f44-808b-de5ddb8812b5",
name: "Christmas discount",
productIds: ["1b9b6c7e-c856-464c-ba64-98c9dd6733b5", "f831aaf4-347a-458f-bb0c-21cf02aeac2e"],
active: true
},
{
id: "5791ae04-a704-4f44-808b-de5ddb8812e6",
name: "Christmas discount 2",
productIds: ["05cdb75d-7984-4dbf-b0f4-d6532163b66d"],
active: true
}
];
At the end i need it like:
const products = [{
id: "05cdb75d-7984-4dbf-b0f4-d6532163b66d",
name: "SANTO - Schnürstiefelette",
price: 199.95,
discount: '5791ae04-a704-4f44-808b-de5ddb8812e6',
},
...
...
You could use map() to transform products array. And find() and includes() to check if discount exists for a product.
const products = [{ id: "05cdb75d-7984-4dbf-b0f4-d6532163b66d", name: "SANTO - Schnürstiefelette", price: 199.95, discount: 0, }, { id: "1b9b6c7e-c856-464c-ba64-98c9dd6733b5", name: "AIR FORCE 1 07 LV8 - Sneaker low", price: 109.95, discount: 0, }, { id: "f831aaf4-347a-458f-bb0c-21cf02aeac2e", name: "DUFF 9.0 - Sporttasche", price: 34.95, discount: 0, }, { id: "471ad894-150b-4a2b-881c-a9a4dbc4b401", name: "Strickpullover", price: 20.99, discount: 0, }, ];
const discounts = [{ id: "5791ae04-a704-4f44-808b-de5ddb8812b5", name: "Christmas discount", productIds: ["1b9b6c7e-c856-464c-ba64-98c9dd6733b5", "f831aaf4-347a-458f-bb0c-21cf02aeac2e"], active: true }, { id: "5791ae04-a704-4f44-808b-de5ddb8812e6", name: "Christmas discount 2", productIds: ["05cdb75d-7984-4dbf-b0f4-d6532163b66d"], active: true } ];
let result = products.map(product => {
let discount = discounts.find(item => item.productIds.includes(product.id));
return {
...product,
"discount": discount ? discount.id : product.discount
};
});
console.log(result);
You could store the discounts in a Map and map the object with a new discount object, if necessary.
var products = [{ id: "05cdb75d-7984-4dbf-b0f4-d6532163b66d", name: "SANTO - Schnürstiefelette", price: 199.95, discount: 0 }, { id: "1b9b6c7e-c856-464c-ba64-98c9dd6733b5", name: "AIR FORCE 1 07 LV8 - Sneaker low", price: 109.95, discount: 0 }, { id: "f831aaf4-347a-458f-bb0c-21cf02aeac2e", name: "DUFF 9.0 - Sporttasche", price: 34.95, discount: 0 }, { id: "471ad894-150b-4a2b-881c-a9a4dbc4b401", name: "Strickpullover", price: 20.99, discount: 0 }],
discounts = [{ id: "5791ae04-a704-4f44-808b-de5ddb8812b5", name: "Christmas discount", productIds: ["1b9b6c7e-c856-464c-ba64-98c9dd6733b5", "f831aaf4-347a-458f-bb0c-21cf02aeac2e"], active: true }, { id: "5791ae04-a704-4f44-808b-de5ddb8812e6", name: "Christmas discount 2", productIds: ["05cdb75d-7984-4dbf-b0f4-d6532163b66d"], active: true }],
ids = discounts.reduce((m, { id, productIds }) => productIds.reduce((n, pid) => n.set(pid, id), m), new Map);
products = products.map(p => Object.assign({}, p, ids.has(p.id) && { discount: ids.get(p.id) }));
console.log(products);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nested loop through both products and discounts array, if the product id is included inside the productIds array of any of the objects in the discounts array, assign the discount id to the product discount.
for (let product of products) {
for (let discount of discounts) {
if (discount.productIds.includes(product.id)){
product.discount = discount.id;
break;
}
}
}

Categories