forked from Chalarangelo/30-seconds-of-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
38a4ede
commit 82cdd26
Showing
1 changed file
with
26 additions
and
0 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
--- | ||
title: indexBy | ||
tags: array,object,intermediate | ||
firstSeen: 2021-06-20T05:00:00-04:00 | ||
--- | ||
|
||
Creates an object from an array, using a function to map each value to a key. | ||
|
||
- Use `Array.prototype.reduce()` to create an object from `arr`. | ||
- Apply `fn` to each value of `arr` to produce a key and add the key-value pair to the object. | ||
|
||
```js | ||
const indexBy = (arr, fn) => | ||
arr.reduce((obj, v, i) => { | ||
obj[fn(v, i, arr)] = v; | ||
return obj; | ||
}, {}); | ||
``` | ||
|
||
```js | ||
indexBy([ | ||
{ id: 10, name: 'apple' }, | ||
{ id: 20, name: 'orange' } | ||
], x => x.id); | ||
// { '10': { id: 10, name: 'apple' }, '20': { id: 20, name: 'orange' } } | ||
``` |