JavaScript - Object.groupBy()

 Object.groupBy() is a powerful method in JavaScript that allows you to group elements from an iterable (such as an array) based on the values returned by a specified callback function. Let’s dive into the details:

  1. What Does Object.groupBy() Do?

    • The Object.groupBy() static method groups elements of a given iterable according to the string values returned by a provided callback function.
    • The resulting object has separate properties for each group, each containing an array with the elements in that group.
    • This method is particularly useful when group names can be represented by strings.
  2. Syntax:

    JavaScript
    Object.groupBy(items, callbackFn)
    
    • items: An iterable (such as an array) whose elements will be grouped.
    • callbackFn: A function executed for each element in the iterable. It should return a value that can be coerced into a property key (string or symbol) indicating the group of the current element.
      • The function is called with the following arguments:
        • element: The current element being processed.
        • index: The index of the current element being processed.
  3. Example: Grouping Food Inventory

    • Let’s say we have an array representing an inventory of different food items:
      JavaScript
      const inventory = [
        { name: "asparagus", type: "vegetables", quantity: 5 },
        { name: "bananas", type: "fruit", quantity: 0 },
        { name: "goat", type: "meat", quantity: 23 },
        { name: "cherries", type: "fruit", quantity: 5 },
        { name: "fish", type: "meat", quantity: 22 },
      ];
      
    • We can group these elements by their type property:
      JavaScript
      const result = Object.groupBy(inventory, ({ type }) => type);
      
    • The resulting object will look like this:
      JavaScript
      {
        vegetables: [{ name: 'asparagus', type: 'vegetables', quantity: 5 }],
        fruit: [
          { name: "bananas", type: "fruit", quantity: 0 },
          { name: "cherries", type: "fruit", quantity: 5 }
        ],
        meat: [
          { name: "goat", type: "meat", quantity: 23 },
          { name: "fish", type: "meat", quantity: 22 }
        ]
      }
      
    • The arrow function simply returns the type of each array element each time it is called.
  4. Note:

    • The elements in the returned object and the original iterable are the same (not deep copies).
    • Changing the internal structure of the elements will be reflected in both the original iterable and the returned object.

Remember, Object.groupBy() is a powerful tool for organizing data and creating meaningful groupings in your JavaScript applications! 🚀🔍📊 1MDN Web Docs - Object.groupBy()

Comments

Popular posts from this blog

New Tech Bloggie

FinTech App