mapObject

JavaScript, Array, Object

Maps the values of an array to an object using a function.

  • 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.
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 }

Recommended snippets

  • zipWith

    JavaScript, Array

    Creates an array of elements, grouped based on the position in the original arrays and using a function to specify how grouped values should be combined.

  • averageBy

    JavaScript, Math

    Calculates the average of an array, after mapping each element to a value using the provided function.

  • sumBy

    JavaScript, Math

    Calculates the sum of an array, after mapping each element to a value using the provided function.