Group items into a Map where each item can have many keys
A blog’s sidebar lists posts under every tag they have, so one post can appear under css and under layout. A plain “group by” puts each item in exactly one group. You need one where an item can belong to several groups at once.
Implement groupByKeys(items, keysOf). It returns a Map from each key to the array of items in that group.
groupByKeys(items, keysOf) // => Map<key, item[]>
keysOf is a function, call it once per item as keysOf(item, index).keysOf is a string, it is a property name, and the result is item[keysOf]. Items that are null or undefined have no keys.undefined means “no key”: an item whose result is undefined or an empty array is not added anywhere, and undefined entries inside an array are skipped. Every other value, including null, is a real key.Map compares them: 1 and '1' are different keys, all NaN values are the same key, 0 and -0 are the same key, and objects are compared by reference.const posts = [
{ title: 'Intro to Flexbox', tags: ['css', 'layout'] },
{ title: 'Closures', tags: ['js'] },
{ title: 'Grid vs Flex', tags: ['css', 'layout', 'css'] },
{ title: 'Draft', tags: [] },
];
groupByKeys(posts, 'tags');
// Map {
// 'css' => [Intro to Flexbox, Grid vs Flex],
// 'layout' => [Intro to Flexbox, Grid vs Flex],
// 'js' => [Closures],
// }
groupByKeys([1.2, 3.7, 1.9, -0.5], Math.floor);
// Map { 1 => [1.2, 1.9], 3 => [3.7], -1 => [-0.5] }
groupByKeys(['apple', 'avocado', 'banana'], (word) => word[0]);
// Map { 'a' => ['apple', 'avocado'], 'b' => ['banana'] }