Last active
March 28, 2024 18:07
-
-
Save gtrabanco/7c97bd41aa74af974fa935bfb5044b6e to your computer and use it in GitHub Desktop.
Object.groupBy polyfill
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
if(typeof Object.groupBy === typeof undefined) { | |
Object.groupBy = (arr, callback) => { | |
return arr.reduce((acc = {}, ...args) => { | |
const key = callback(...args); | |
acc[key] ??= [] | |
acc[key].push(args[0]); | |
return acc; | |
}, {}) | |
} | |
} | |
// There are better approaches using loops directly instead of reduce | |
// Example: | |
console.log( | |
Object.groupBy( | |
[1, 2, 3, 4, 5, 6], | |
(v) => v % 2 === 0 ? 'even': 'odd' | |
) | |
); |
This should not be with
prototype
. JustObject.groupBy
Updated. Thank you.
Can you explain why or give a link to know the explanation? 🙏
The original API is without prototype. Link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/groupBy
Here is basic usage from documentation:
Object.groupBy(items, callbackFn)
Anyway, by removing prototype
your code works very well. I have used it as a polyfill for Google Chrome >= v116.
Thank you!
I also update to check first if no defined to avoid forget it as I did in my project 😅
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This should not be with
prototype
. JustObject.groupBy