Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ```javascript
- const products = [
- { id: 1, name: 'Laptop', price: 1200, category: 'Electronics', stock: 5 },
- { id: 2, name: 'Smartphone', price: 800, category: 'Electronics', stock: 12 },
- { id: 3, name: 'Coffee Maker', price: 150, category: 'Appliances', stock: 8 },
- { id: 4, name: 'Desk Chair', price: 250, category: 'Furniture', stock: 15 },
- { id: 5, name: 'Monitor', price: 300, category: 'Electronics', stock: 0 },
- ];
- /**
- * FILTER: Get only electronics that are in stock
- */
- const availableElectronics = products.filter(product =>
- product.category === 'Electronics' && product.stock > 0
- );
- /**
- * MAP: Create a list of formatted strings with a 10% discount price applied
- */
- const productPriceLabels = products.map(product => {
- const discountedPrice = (product.price * 0.9).toFixed(2);
- return `${product.name} is now $${discountedPrice}`;
- });
- /**
- * REDUCE: Calculate the total inventory value
- */
- const totalInventoryValue = products.reduce((accumulator, product) => {
- return accumulator + (product.price * product.stock);
- }, 0);
- /**
- * CHAINED: Get the total cost of all electronics (Filter -> Map -> Reduce)
- */
- const totalElectronicsCost = products
- .filter(p => p.category === 'Electronics')
- .map(p => p.price)
- .reduce((sum, price) => sum + price, 0);
- // Usage
- console.log('Available Electronics:', availableElectronics);
- console.log('Price Labels:', productPriceLabels);
- console.log('Total Inventory Value:', totalInventoryValue);
- console.log('Sum of Electronics Prices:', totalElectronicsCost);
- ```
Advertisement
Add Comment
Please, Sign In to add comment