Advertisement
Guest User

Untitled

a guest
Feb 23rd, 2020
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.88 KB | None | 0 0
  1. `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:
  2.  
  3. function groupBy(objectArray, property) {
  4. // The object we'll return with properties for the groups
  5. let result = {}
  6. // Loop through the array
  7. for (const obj of objectArray) {
  8. // Get the key value
  9. let key = obj[property]
  10. // If the result doesn't have an entry for that yet, create one
  11. if (!result[key]) {
  12. result[key] = []
  13. }
  14. // Add this entry to that entry
  15. result[key].push(obj)
  16. }
  17. // Return the grouped result
  18. return result;
  19. }
  20.  
  21. 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