Skip to content

Instantly share code, notes, and snippets.

@ArtemAvramenko
Last active September 2, 2022 09:06
Show Gist options
  • Save ArtemAvramenko/d92c92ff1b74cbc55be226dcabff90cc to your computer and use it in GitHub Desktop.
Save ArtemAvramenko/d92c92ff1b74cbc55be226dcabff90cc to your computer and use it in GitHub Desktop.
TypeScript convert array to dictionary
static toDictionary<TItem>(
array: TItem[],
getKey: (item: TItem) => number): { [id: number]: TItem };
static toDictionary<TItem, TValue>(
array: TItem[],
getKey: (item: TItem) => number,
getValue: (item: TItem) => TValue): { [id: number]: TValue };
static toDictionary<TItem>(
array: TItem[],
getKey: (item: TItem) => string): { [id: string]: TItem };
static toDictionary<TItem, TValue>(
array: TItem[],
getKey: (item: TItem) => string,
getValue: (item: TItem) => TValue): { [id: string]: TValue };
static toDictionary<TItem>(
array: TItem[],
getKey: (item: TItem) => number | string,
getValue?: (item: TItem) => any): any { // eslint-disable-line @typescript-eslint/no-explicit-any
const result = {} as any; // eslint-disable-line @typescript-eslint/no-explicit-any
if (array) {
if (getValue) {
array.forEach(_ => result[getKey(_)] = getValue(_));
}
else {
array.forEach(_ => result[getKey(_)] = _);
}
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment