Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save himynameisdave/babdb1b4eeb427d3a21f406d34e22523 to your computer and use it in GitHub Desktop.
Save himynameisdave/babdb1b4eeb427d3a21f406d34e22523 to your computer and use it in GitHub Desktop.
Reduce your fears about .reduce() - twentySomethingsLongFullNames-reduce.js
const isInTwenties = user => user.age >= 20 && user.age < 30;
const makeFullName = user => `${user.firstName} ${user.lastName}`;
const isAtLeastTenChars = fullName => fullName.length >= 10;
const twentySomethingsLongFullNames = users.reduce(
// The first arg that .reduce takes is the reducer function
// It has the signature:
// - `accumulator` - this is what you build up as you move through the array
// - `user` - this is the reference to the item in the array we are currently on
// - `index` - not used here, but you can get the index of the current place in the array you are
// - `array` - not used here, but this refers to the original array if you need a ref to it
(accumulator, user) => {
  const fullName = makeFullName(user);
  if (isInTwenties(user) && isAtLeastTenChars(fullName)) accumulator.push(fullName);
return accumulator
},
// The second argument (optional) is the initial value
// This will be the value of `accumulator` in the first iteration of `.reduce`
[]
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment