Skip to content

Instantly share code, notes, and snippets.

@codebender828
Created May 28, 2020 03:28
Show Gist options
  • Save codebender828/f6adc584f4bfe1311e1a2617805e4601 to your computer and use it in GitHub Desktop.
Save codebender828/f6adc584f4bfe1311e1a2617805e4601 to your computer and use it in GitHub Desktop.
What do you name this function? It transforms an array of objects into an object with `values` and an `allKeys` array.
// So I'm struggling to name this function so I called it `indexArrayBy`
// but it's really doing more. Here's a link to it's demo:
// Demo: https://playcode.io/612180/
/**
* Transforms an array of objects into an object containing the values
* indexed by a unique property on each object, e.g. id and
* an array containing all the keys (So you get the keys).
*
* @param {Array<Object>} array Array of objects
* @param {String} key Property by which to key all objects
* @returns {{ values: Object, allKeys: Array<Number|String> }}
*/
function indexArrayBy (array, key = 'id') {
const allKeys = new Set()
const values = array.reduce((acc, cur, index) => {
if (!cur[key]) {
throw new Error(`Key "${key}" does not exist in the object at index "${index}"`)
}
if (acc[cur[key]]) {
console.warn(`Key provided "${key}" is not unique. Will overwrite previously set values.`)
}
allKeys.add(cur[key])
acc[cur[key]] = cur
return acc
}, {})
return {
values,
allKeys: [...allKeys]
}
}
@codebender828
Copy link
Author

See it action here: https://playcode.io/612180/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment