Skip to content

Instantly share code, notes, and snippets.

@Sangrene
Created December 10, 2019 16:32
Show Gist options
  • Save Sangrene/94747f23f90abbbd22a375ecb56dbc10 to your computer and use it in GitHub Desktop.
Save Sangrene/94747f23f90abbbd22a375ecb56dbc10 to your computer and use it in GitHub Desktop.
Typescript function to extract item & index from an array with items containing an "id" property
const findItemAndIndexById = <T extends { id: string }>(
id: string,
tabWithId: T[]
):
| {
item: T;
index: number;
}
| undefined => {
let itemIndex = -1;
const item = tabWithId.find((item, index) => {
itemIndex = index;
return item.id === id;
});
if (item) {
return {
item,
index: itemIndex
};
} else return undefined;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment