Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Wouldn't do it with variable, since it will make your function impure [1]

1 : http://www.nicoespeon.com/en/2015/01/pure-functions-javascri...



That's the GP's point though: it already is impure! If you rewrite as

    let acc = {...}
    footballPlayers.reduce(...,acc)
It should become clear: acc is an external variable that got mutated by the reduce.


Indeed. A pure function should not depend on and / or mutate external variables.

I'd do it like this (yay for one-ish-liners!):

  const playersByCountry = footballPlayers.reduce((acc, player) => {
    return {...acc, [player.country]: [...(acc[player.country] || []), player]};
  }, {});




Consider applying for YC's Summer 2026 batch! Applications are open till May 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: