Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Total price
- const items = [
- { name: 'Apple', price: 1 },
- { name: 'Orange', price: 2 },
- { name: 'Mango', price: 3 },
- ];
- const totalPrice = items.reduce((accumulator ,item, index, array) => {
- return accumulator += item.price;
- }, 0)
- console.log(totalPrice);
- // 6
- // How to Group Similar Items Together
- const items = [
- { name: 'Apple', category: 'Fruit' },
- { name: 'Onion', category: 'Vegetable' },
- { name: 'Orange', category: 'Fruit' },
- { name: 'Lettuce', category: 'Vegetable' },
- ];
- const groupedItems = items.reduce((accumulator, item) => {
- const category = item.category;
- if (!accumulator[category]) {
- accumulator[category] = []
- }
- accumulator[category].push(item.name);
- return accumulator
- }, {})
- console.log(groupedItems);
- // { Fruit: [ 'Apple', 'Orange' ], Vegetable: [ 'Onion', 'Lettuce' ] }
- // How to Remove Duplicates
- const items = [1, 2, 3, 1, 2, 3, 7, 8, 7];
- const noDuplicateItems = items.reduce((accumulator, item) => {
- if (!accumulator.includes(item)) {
- accumulator.push(item);
- }
- return accumulator;
- }, []);
- console.log(noDuplicateItems);
- // [ 1, 2, 3, 7, 8 ]
Add Comment
Please, Sign In to add comment