Created
December 19, 2022 09:22
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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