New upcoming array method called groupBy()

The groupBy() method is a forthcoming addition to the JavaScript Array object, currently positioned at Stage 3 within the TC39 process.

✅ Its advancement to Stage 3 indicates a high likelihood of being incorporated into the ECMAScript standard soon.

✅ groupBy() expects a callback function as its parameter.

✅ The callback function is invoked for each array element, and it should yield a string or symbol representing the group to which the element belongs.

Syntax

Object.groupBy(items, callbackFn)

Example #1

const result = Object.groupBy(inventory, ({ type }) => type);

Result is:
{
  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 }
  ]
}        

Example #2

const number = [1, 2, 3, 4, 5, 6, 7, 8];

const groupBy = Object.groupBy(number, (num, index) => {

    return num % 2 === 0 ? 'even' : 'odd'

})

console.log('groupBy', groupBy);

Result is:
{
    "odd": [1, 3, 5, 7],
    "even": [2, 4, 6, 8]
}        

for more detail


To view or add a comment, sign in

Others also viewed

Explore topics