Creates an object from an array, using a function to map each value to a key.
Array.prototype.reduce()
to create an object from arr
.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' } }
Would you like to help us improve 30 seconds of code?Take a quick survey
JavaScript, Array
Creates an object from an array, using the specified key and excluding it from each value.
JavaScript, Array
Maps the values of an array to an object using a function.
JavaScript, Array
Finds the highest index at which a value should be inserted into an array in order to maintain its sort order, based on a provided iterator function.