641 B
641 B
title, tags, expertise, cover, firstSeen, lastUpdated
| title | tags | expertise | cover | firstSeen | lastUpdated |
|---|---|---|---|---|---|
| Map array to object | array,object | intermediate | blog_images/two-lighthouses.jpg | 2017-12-18T12:11:58+02:00 | 2020-10-21T21:54:53+03:00 |
Maps the values of an array to an object using a function.
- Use
Array.prototype.reduce()to applyfnto each element inarrand combine the results into an object. - Use
elas the key for each property and the result offnas the value.
const mapObject = (arr, fn) =>
arr.reduce((acc, el, i) => {
acc[el] = fn(el, i, arr);
return acc;
}, {});
mapObject([1, 2, 3], a => a * a); // { 1: 1, 2: 4, 3: 9 }