invertBy
object
This method is like invert except that the inverted object is generated from the results of running each element of object thru iteratee.
Installation
Import
import { invertBy } from '@tulx/utils';Source Code
Implementation
/**
* This method is like invert except that the inverted object is generated from the results of running each element of object thru iteratee.
*
* @param object - The object to invert.
* @param iteratee - The iteratee invoked per element.
* @returns Returns the new inverted object.
*
* @example
* ```ts
* const object = { 'a': 1, 'b': 2, 'c': 1 };
* invertBy(object); // { '1': ['a', 'c'], '2': ['b'] }
* invertBy(object, (value) => 'group' + value); // { 'group1': ['a', 'c'], 'group2': ['b'] }
* ```
*/
export function invertBy<T>(
object: Record<string, T>,
iteratee?: (value: T) => string
): Record<string, string[]> {
const result: Record<string, string[]> = {};
const getValue = iteratee || ((value: T) => String(value));
for (const key in object) {
if (Object.prototype.hasOwnProperty.call(object, key)) {
const value = getValue(object[key]);
if (!result[value]) {
result[value] = [];
}
result[value].push(key);
}
}
return result;
}
Example
import { invertBy } from '@tulx/utils';
const object = { 'a': 1, 'b': 2, 'c': 1 };
invertBy(object); // { '1': ['a', 'c'], '2': ['b'] }
invertBy(object, (value) => 'group' + value); // { 'group1': ['a', 'c'], 'group2': ['b'] }Related Functions
assign
Assigns own enumerable string keyed properties of source objects to the destination object.
assignIn
This method is like assign except that it iterates over own and inherited source properties.
assignInWith
This method is like assignIn except that it accepts customizer which is invoked to produce the assigned values.
assignWith
This method is like assign except that it accepts customizer which is invoked to produce the assigned values.
at
Creates an array of values corresponding to paths of object.
create
Creates an object that inherits from the prototype object.