Merge pull request #1113 from ezracelli/master
[FIX] update implementation & explanation for mapObject
This commit is contained in:
@ -1,20 +1,21 @@
|
|||||||
---
|
---
|
||||||
title: mapObject
|
title: mapObject
|
||||||
tags: array,object,advanced
|
tags: array,object,intermediate
|
||||||
---
|
---
|
||||||
|
|
||||||
Maps the values of an array to an object using a function, where the key-value pairs consist of the stringified value as the key and the mapped value.
|
Maps the values of an array to an object using a function, where the key-value pairs consist of the original value as the key and the result of the function as the value.
|
||||||
|
|
||||||
Use an anonymous inner function scope to declare an undefined memory space, using closures to store a return value. Use a new `Array` to store the array with a map of the function over its data set and a comma operator to return a second step, without needing to move from one context to another (due to closures and order of operations).
|
Use `Array.prototype.reduce()` to apply `fn` to each element in `arr` and combine the results into an object.
|
||||||
|
Use `el` as the key for each property and the result of `fn` as the value.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const mapObject = (arr, fn) =>
|
const mapObject = (arr, fn) =>
|
||||||
(a => (
|
arr.reduce((acc, el, i) => {
|
||||||
(a = [arr, arr.map(fn)]), a[0].reduce((acc, val, ind) => ((acc[val] = a[1][ind]), acc), {})
|
acc[el] = fn(el, i, arr);
|
||||||
))();
|
return acc;
|
||||||
|
}, {});
|
||||||
```
|
```
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const squareIt = arr => mapObject(arr, a => a * a);
|
mapObject([1, 2, 3], a => a * a); // { 1: 1, 2: 4, 3: 9 }
|
||||||
squareIt([1, 2, 3]); // { 1: 1, 2: 4, 3: 9 }
|
```
|
||||||
```
|
|
||||||
|
|||||||
Reference in New Issue
Block a user