DEV Community

Discussion on: Map, Filter, Reduce and others Arrays Iterators You Must Know to Become an Algorithms Wizard

Collapse
 
nki2 profile image
NISHIGAKI Nobuyuki

Great article! I love playing with array iterators too!

For my two cents, I would write this chunk

const sumPopulationButNotChina = population.reduce((acc, val) => {
  return val.country !== 'China' ? acc + val.pop : acc;
}, 0);

to something like this

const sumPopulationButNotChina = population
    .filter(val => val.country !== 'China')
    .reduce((acc, val) => acc + val.pop, 0);

in order to evolve it in a real world code like this.

const countryFilter = country => val => val.country !== country;
const sumPopulationButNotChina = population
    .filter(countryFilter('China'))
    .reduce((acc, val) => acc + val.pop, 0);
Collapse
 
uptheirons78 profile image
Mauro Bono

Your 2 cents are gold, cause you are completely right and in a real case scenario I will use your same path with filter() and reduce().

In this case I just wanted to show it is possible to do it only with reduce() 😉😉😉