Skip to content

Instantly share code, notes, and snippets.

@jenux
Last active March 30, 2022 03:40
Show Gist options
  • Select an option

  • Save jenux/8c0682fabc41705ece771ac6f207d793 to your computer and use it in GitHub Desktop.

Select an option

Save jenux/8c0682fabc41705ece771ac6f207d793 to your computer and use it in GitHub Desktop.
[Index array based on function] #Array #Object #30secondsofcode
const indexBy = (arr, fn) => arr.reduce((obj, val, i) => {
obj[fn(val, i, arr)] = val
return obj
}, {})
// Examples
indexBy([
{ id: 10, name: 'apple' },
{ id: 20, name: 'orange' }
], x => x.id)
/*
{
'10': { id: 10, name: 'apple' },
'20': { id: 20, name: 'orange' }
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment