Created
December 10, 2019 16:32
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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