til

How to group an array into a Map

typescriptjavascript

While reviewing the Safari 16.4 release notes I noticed a new method for array and array like objects.

Basically it iterates throught an array and returns a Map object indexed by the returned value of the groupToMap callback.

const posts = [
  { slug: "something-new", favorites: 3 },
  { slug: "weird-bug-thingy", favorites: 2 },
  { slug: "some-cash-please", favorites: 2 },
  { slug: "unpopular-opinion", favorites: 1 },
  { slug: "how-to-make-money", favorites: 3 }
];

posts.groupToMap(({ favorites }) => favorites);

That will return a Map object like this:

[
  [
    3,
    [
      { slug: "something-new", favorites: 3 },
      { slug: "how-to-make-money", favorites: 3 }
    ]
  ],
  [
    2,
    [
      { slug: "weird-bug-thingy", favorites: 2 },
      { slug: "some-cash-please", favorites: 2 }
    ]
  ],
  [1, [{ slug: "unpopular-opinion", favorites: 1 }]]
]

Until it's officially polyfilled, here's an ambient declaration that you could add to your global.d.ts file to make it work with TypeScript:

declare global {
  interface Array<T> {
    groupToMap<GroupName>(
      cb: (value: T) => GroupName,
      index?: number,
      origArray?: T[]
    ): Map<GroupName, T>;
  }
}

Note: On sparse arrays empty values are treated as undefined.

I've made a CodeSandbox to play with it