xerocool-101

001 reduce method

Apr 19th, 2025 (edited)
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JavaScript 1.14 KB | Software | 0 0
  1. // Total price
  2. const items = [
  3.   { name: 'Apple', price: 1 },
  4.   { name: 'Orange', price: 2 },
  5.   { name: 'Mango', price: 3 },
  6. ];
  7.  
  8. const totalPrice = items.reduce((accumulator ,item, index, array) => {
  9.   return accumulator += item.price;
  10. }, 0)
  11.  
  12. console.log(totalPrice);
  13. // 6
  14.  
  15. // How to Group Similar Items Together
  16. const items = [
  17.   { name: 'Apple', category: 'Fruit' },
  18.   { name: 'Onion', category: 'Vegetable' },
  19.   { name: 'Orange', category: 'Fruit' },
  20.   { name: 'Lettuce', category: 'Vegetable' },
  21. ];
  22.  
  23. const groupedItems = items.reduce((accumulator, item) => {
  24.   const category = item.category;
  25.   if (!accumulator[category]) {
  26.     accumulator[category] = []
  27.   }
  28.   accumulator[category].push(item.name);
  29.   return accumulator
  30. }, {})
  31.  
  32. console.log(groupedItems);
  33. // { Fruit: [ 'Apple', 'Orange' ], Vegetable: [ 'Onion', 'Lettuce' ] }
  34.  
  35. // How to Remove Duplicates
  36. const items = [1, 2, 3, 1, 2, 3, 7, 8, 7];
  37.  
  38. const noDuplicateItems = items.reduce((accumulator, item) => {
  39.   if (!accumulator.includes(item)) {
  40.     accumulator.push(item);
  41.   }
  42.   return accumulator;
  43. }, []);
  44.  
  45. console.log(noDuplicateItems);
  46. // [ 1, 2, 3, 7, 8 ]
  47.  
Tags: JavaScript
Add Comment
Please, Sign In to add comment