JavaScript proposal array grouping

ยท 2 min read
JavaScript proposal array grouping

At the moment of this writing two brand-new array methods named groupBy and groupByToMap are getting closer to official release since they are in stage 3.

For years, we used to pull Lodash groupBy or even write our own custom utility methods to group array items, so now it seems JavaScript is going to provide this out of the box.

Let's see an example for groupBy:

const array = [-8, -3, 1, 2, 3, -4, 5];

// groupBy groups items by arbitrary key.
// In this case, we're grouping by positive/negative items
const groups = array.groupBy((num, index, array) => {
  return num > 0 ? 'positive': 'negative';
});

console.log(groups);

// { negative: [-8, -3, -4], positive: [1, 2, 3, 5] }

We can also use groupByToMap to end up with a Map:

// groupByToMap returns items in a Map, and is useful for grouping using an object key.
const negative  = { negative: true };
const positive = { positive: true };
const groupsMap = array.groupByToMap((num, index, array) => {
  return num > 0 ? positive : negative;
});

console.log(groupsMap);
// =>  Map { {negative: true}: [-8, -3, -4], {positive: true}: [1, 2, 3, 5] }

Here is a Codesandbox you can use to play with these two pretty helpful methods straight ahead.

Notice the imported modules core-js/actual/array/group-by and core-js/actual/array/group-by-to-map I had to pull from core-js to make these two work. Cheers!!

Did you like this one?

I hope you really did...

Marios_thumb

Newsletter

Get notified about latest posts and updates once a week!!