Files
30-seconds-of-code/snippets/js/s/map-array-to-object.md
Angelos Chalaris 9d032ce05e Rename js snippets
2023-05-19 20:23:47 +03:00

602 B

title, type, language, tags, cover, dateModified
title type language tags cover dateModified
Map array to object snippet javascript
array
object
two-lighthouses 2020-10-21T21:54:53+03:00

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;
  }, {});
mapObject([1, 2, 3], a => a * a); // { 1: 1, 2: 4, 3: 9 }