Skip to content

Instantly share code, notes, and snippets.

@srph
Last active May 19, 2019 06:58
Show Gist options
  • Select an option

  • Save srph/dddc8afa71d96fa736cbc5dcc3515d85 to your computer and use it in GitHub Desktop.

Select an option

Save srph/dddc8afa71d96fa736cbc5dcc3515d85 to your computer and use it in GitHub Desktop.
JS: Make it easy to search for an item inside an array
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