index-array-by is a lightweight utility function, currently at version 1.4.2, designed for efficiently indexing JavaScript arrays of objects based on various criteria. It enables developers to transform a flat list into a nested object or array structure. Key differentiators include its flexibility in defining index keys, supporting string property names, an array of property names for hierarchical indexing, or custom accessor functions for complex key generation. The library also provides robust handling for duplicate keys, allowing the user to specify whether each index key should map to a single item (potentially overwriting duplicates if not unique) or an array of all matching items (the default behavior). Furthermore, it supports custom transformation functions for reducing multiple items into a single value, and an optional parameter to flatten the output into an array of { keys, vals } objects. It is actively maintained, shipping with TypeScript types to enhance developer experience and provide strong type checking in modern JavaScript environments.
npm install index-array-byVerified import paths — ran on the pinned version, not inferred.
Demonstrates indexing an array of objects by a string property, resulting in an object where each key points to a single item, preventing array wrapping.
Call indexBy with `indexBy(list, keyAccessor, false)` to ensure single-item values.
Ensure your keyAccessor generates unique keys or set 'multiItem' to 'true' (default) to collect all items into an array, or provide a custom reducer function for 'multiItem' to handle conflicts.
Ensure custom key accessor functions explicitly return string or symbol values for predictable object indexing.
Use `import indexBy from 'index-array-by';` for ESM or ensure proper CommonJS require if not in an ESM environment (e.g., `const indexBy = require('index-array-by');`).Set the third argument 'multiItem' to 'false': `indexBy(yourArray, 'yourKey', false)`.
If all items sharing a key should be kept, set 'multiItem' to 'true'. If a single item is desired, ensure keys are unique or provide a custom reducer function to 'multiItem' to define how multiple items are consolidated.
No dependency data recorded yet.