3 ms·
Great article, but questionable formatting: `return {name: player.name, age: player.age }` It also seems wrong to mutate the accumulator in the reduce example,
by namanyayg 9y ago
Great article, but questionable formatting: `return {name: player.name, age: player.age }`
It also seems wrong to mutate the accumulator in the reduce example, it would just be simpler to use `forEach` and use a variable defined outside if you're going to write code this way?
- drinchev 9y agoWouldn't do it with variable, since it will make your function impure [1] 1 : http://www.nicoespeon.com/en/2015/01/pure-functions-javascript/ http://www.nicoespeon.com/en/2015/01/pure-functions-javascri...
- pdpi 9y agoThat'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.
- bestest 9y agoIndeed. 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]}; }, {});