0 points

mapObject(JavaScript, Array, Object, Intermediate)


dashboard

Wed Apr 29 2020 11:26:22 GMT+0000 (UTC)

Posted by @Bubbly #javascript

const mapObject = (arr, fn) =>
  arr.reduce((acc, el, i) => {
    acc[el] = fn(el, i, arr);
    return acc;
  }, {});
  
EXAMPLES
mapObject([1, 2, 3], a => a * a); // { 1: 1, 2: 4, 3: 9 }                                
                                
content_copy Copy

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.

https://www.30secondsofcode.org/js/s/map-object/