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

719 B

title, type, language, tags, author, cover, dateModified
title type language tags author cover dateModified
Index array based on function snippet javascript
array
object
chalarangelo guitar-living-room 2021-06-20T05:00:00-04:00

Creates an object from an array, using a function to map each value to a key.

  • Use Array.prototype.reduce() to create an object from arr.
  • Apply fn to each value of arr to produce a key and add the key-value pair to the object.
const indexBy = (arr, fn) =>
  arr.reduce((obj, v, i) => {
    obj[fn(v, i, arr)] = v;
    return obj;
  }, {});
indexBy([
  { id: 10, name: 'apple' },
  { id: 20, name: 'orange' }
], x => x.id);
// { '10': { id: 10, name: 'apple' }, '20': { id: 20, name: 'orange' } }