Last active
May 19, 2019 06:58
-
-
Save srph/dddc8afa71d96fa736cbc5dcc3515d85 to your computer and use it in GitHub Desktop.
JS: Make it easy to search for an item inside an array
This file contains hidden or 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
| interface SearchMap { | |
| [key: string]: boolean | |
| } | |
| /** | |
| * Make it easy to search for an item inside an array | |
| * | |
| * @input | |
| * [{ id: 5 }, { id: 6 }, { id: 7 }, { id: 32 }] | |
| * @output | |
| * { 5: true, 6: true, 7: true, 32: true } | |
| * | |
| * @example | |
| * const members = toSearchObject(party.members, 'id') | |
| * const isMember = members[user.id] | |
| * | |
| * @param array | |
| * @param property | |
| */ | |
| export default function toSearchObject<T = any>(array: T[], property: string): SearchMap { | |
| return array.reduce((prev: SearchMap, current: T) => { | |
| prev[current[property]] = true | |
| return prev | |
| }, {}) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment