Takes an array of objects and a specific key and returns an object with keys corresponding to the values of that key. The values are arrays of objects that share the same value of that key. You can optionally pass in a boolean to apply case sensitivity. (false by default)
function groupByKeyValue<T extends object, U extends keyof T>(
arr: T[],
key: U,
isCaseSensitive = false
)
// Example:
const arr = [
{ name: "John", age: 30},
{ name: "Sarah", age: 32 },
{ name: "John", age: 28 },
{ name: "Beth", age: 23}
]
groupByKeyValue(arr, "name")
//=>
{
"John": [{ name: "John", age: 30 }, {name: "John", age: 28 }]
"Sarah": [{ name: "Sarah", age: 32 }]
"Beth": [{name: "Beth", age: 23 }]
}