Last active
March 30, 2022 03:40
-
-
Save jenux/8c0682fabc41705ece771ac6f207d793 to your computer and use it in GitHub Desktop.
[Index array based on function] #Array #Object #30secondsofcode
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
| 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