DEV Community

Raju Saha
Raju Saha

Posted on

Exciting New Features in ECMAScript 2024 - groupBy() πŸŽ—οΈ

The latest version of JavaScript, ECMAScript 2024, became an official standard on June 26, 2024, thanks to the 127th ECMA General Assembly.

It has included six new features

  • Grouping synchronous iterable
  • Promise.withResolvers()
  • Regular expression flag /v
  • New features for ArrayBuffers and SharedArrayBuffers
  • Ensuring that strings are well-formed
  • Atomics.waitAsync()

Grouping synchronously iterable

groupBy() : Object.groupBy() Map.groupBy()
The Object.groupBy() method takes an object and a callback function. It groups the object's elements into a new object based on the strings returned by the callback function for each element. The original object remains unchanged.

const stationary=[
  {name:'Pencil',qty:100},
  {name:'Pen',qty:50},
  {name:'Rubber',qty:300},
  {name:'Notebook',qty:150},
  {name:'Scale',qty:0},
  {name:'Color Pencil',qty:0},
]
function callbackFun({qty}){
  return qty>0?'available':'notAvailable'
}
const result=Object.groupBy(stationary,callbackFun);
console.log(result);

//output
/*
{
  available: [
    { name: 'Pencil', qty: 100 },
    { name: 'Pen', qty: 50 },
    { name: 'Rubber', qty: 300 },
    { name: 'Notebook', qty: 150 }
  ],
  notAvailable: [
    { name: 'Scale', qty: 0 },
    { name: 'Color Pencil', qty: 0 }
  ]
}
*/
Enter fullscreen mode Exit fullscreen mode

The Map.groupBy() method groups elements from an object based on strings returned by a callback function. It creates a new Map object with these groups, leaving the original object unchanged.

//...
const result=Map.groupBy(stationary,callbackFun);
console.log(result);

//output
/*
Map(2) {
  'available' => [
    { name: 'Pencil', qty: 100 },
    { name: 'Pen', qty: 50 },
    { name: 'Rubber', qty: 300 },
    { name: 'Notebook', qty: 150 }
  ],
  'notAvailable' => [
    { name: 'Scale', qty: 0 },
    { name: 'Color Pencil', qty: 0 }
  ]
}
*/
Enter fullscreen mode Exit fullscreen mode

Checkout next Post for other features

Reference Ecma International approves ECMAScript 2024: What’s new?

Happy Coding !!

Top comments (0)