Created
May 18, 2021 23:34
-
-
Save monsat/8ded56b5e79f9bc21914c6b87c8c4b45 to your computer and use it in GitHub Desktop.
配列に入ったオブジェクトのなかから指定の id のオブジェクトを取り出し、残りとともに返す関数(複数みつかった場合はエラー)
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 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