Skip to content

Instantly share code, notes, and snippets.

@jkohlin
Created December 19, 2022 09:22
Show Gist options
  • Save jkohlin/afe40a870ef86e0c17de8c4ed712330f to your computer and use it in GitHub Desktop.
Save jkohlin/afe40a870ef86e0c17de8c4ed712330f to your computer and use it in GitHub Desktop.
From array of objects to an object with keys taken from a value in each object
/**
* Description
* @param {Array} list
* @param {string} key
* @returns {any}
*/
export const groupBy = (list, key) => {
return (
list?.reduce((acc, row) => {
// acc = {}, row[key] = exv 'SITE' (key='listType') acc.SITE är undefined från början, men propen skapas iom exp=exp och sätts till [] eftersom acc[row[key]] är undefined. Nästa varv finns propen med arrayen med en rad i.
; (acc[row[key]] = acc[row[key]] || []).push(row)
return acc
}, {}) || {}
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment