Skip to content

Instantly share code, notes, and snippets.

@monsat
Created May 18, 2021 23:34
Show Gist options
  • Save monsat/8ded56b5e79f9bc21914c6b87c8c4b45 to your computer and use it in GitHub Desktop.
Save monsat/8ded56b5e79f9bc21914c6b87c8c4b45 to your computer and use it in GitHub Desktop.
配列に入ったオブジェクトのなかから指定の id のオブジェクトを取り出し、残りとともに返す関数(複数みつかった場合はエラー)
const pickAndFilter = <T extends { id: string }>(id: string, items: Array<T>): [T | undefined, T[]] => {
const picked: T[] = []
const remained = items.reduce((accumulator: T[], item) => {
if (item.id === id) {
picked.push(item)
} else {
accumulator.push(item)
}
return accumulator
}, [])
if (picked.length > 1) {
throw new Error('Picked multiple')
}
return [picked[0], remained]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment