Merge pull request #87 from kingdavidmartins/add-pick-method
add pick code snippet
This commit is contained in:
15
README.md
15
README.md
@ -45,6 +45,7 @@
|
|||||||
* [Median of array of numbers](#median-of-array-of-numbers)
|
* [Median of array of numbers](#median-of-array-of-numbers)
|
||||||
* [Object from key value pairs](#object-from-key-value-pairs)
|
* [Object from key value pairs](#object-from-key-value-pairs)
|
||||||
* [Percentile](#percentile)
|
* [Percentile](#percentile)
|
||||||
|
* [Pick](#pick)
|
||||||
* [Pipe](#pipe)
|
* [Pipe](#pipe)
|
||||||
* [Powerset](#powerset)
|
* [Powerset](#powerset)
|
||||||
* [Promisify](#promisify)
|
* [Promisify](#promisify)
|
||||||
@ -454,6 +455,20 @@ const percentile = (arr, val) =>
|
|||||||
// percentile([1,2,3,4,5,6,7,8,9,10], 6) -> 55
|
// percentile([1,2,3,4,5,6,7,8,9,10], 6) -> 55
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### Pick
|
||||||
|
|
||||||
|
Use `.reduce()` to convert the filtered/picked keys back to a object with the corresponding key:value pair if the key exist in the obj.
|
||||||
|
|
||||||
|
```js
|
||||||
|
const pick = (obj, arr) => arr.reduce((acc, curr) => (curr in obj && (acc[curr] = obj[curr]), acc), {});
|
||||||
|
|
||||||
|
// const object = { 'a': 1, 'b': '2', 'c': 3 };
|
||||||
|
// pick(object, ['a', 'c']) -> { 'a': 1, 'c': 3 }
|
||||||
|
|
||||||
|
// pick(object, ['a', 'c'])['a'] -> 1
|
||||||
|
// pick(object, ['a', 'c'])['c'] -> 3
|
||||||
|
|
||||||
|
```
|
||||||
### Pipe
|
### Pipe
|
||||||
|
|
||||||
Use `Array.reduce()` to pass value through functions.
|
Use `Array.reduce()` to pass value through functions.
|
||||||
|
|||||||
14
snippets/pick.md
Normal file
14
snippets/pick.md
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
### Pick
|
||||||
|
|
||||||
|
Use `.reduce()` to convert the filtered/picked keys back to a object with the corresponding key:value pair if the key exist in the obj.
|
||||||
|
|
||||||
|
```js
|
||||||
|
const pick = (obj, arr) => arr.reduce((acc, curr) => (curr in obj && (acc[curr] = obj[curr]), acc), {});
|
||||||
|
|
||||||
|
// const object = { 'a': 1, 'b': '2', 'c': 3 };
|
||||||
|
// pick(object, ['a', 'c']) -> { 'a': 1, 'c': 3 }
|
||||||
|
|
||||||
|
// pick(object, ['a', 'c'])['a'] -> 1
|
||||||
|
// pick(object, ['a', 'c'])['c'] -> 3
|
||||||
|
|
||||||
|
```
|
||||||
Reference in New Issue
Block a user