Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- `reduce` makes that function much more complex-seeming than it actually is. (`reduce` is hugely overused, and almost always the wrong tool.) Here's the same function without the unnecessary `reduce`, with explanation:
- function groupBy(objectArray, property) {
- // The object we'll return with properties for the groups
- let result = {}
- // Loop through the array
- for (const obj of objectArray) {
- // Get the key value
- let key = obj[property]
- // If the result doesn't have an entry for that yet, create one
- if (!result[key]) {
- result[key] = []
- }
- // Add this entry to that entry
- result[key].push(obj)
- }
- // Return the grouped result
- return result;
- }
- The `reduce` version just passes `result` around (as `acc`) by receiving it as the first argument to the callback (because that's how `reduce` works) and then returning it from the callback.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement