Skip to content

Instantly share code, notes, and snippets.

@midudev
Created October 7, 2016 17:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save midudev/caee69fe6b159514f1d2cd0f8dad5a09 to your computer and use it in GitHub Desktop.
Save midudev/caee69fe6b159514f1d2cd0f8dad5a09 to your computer and use it in GitHub Desktop.
Example about how to use reduce to map and filter an array with one iteration
const MULTIMEDIA_IMAGE_TYPE_ID = 12
const multimedias = [
{ mediumSizeUrl: 'dog.jpg', typeId: 2 },
{ mediumSizeUrl: 'panda.jpg', typeId: 12 },
{ mediumSizeUrl: 'koala.jpg', typeId: 12 },
{ mediumSizeUrl: 'trex.jpg', typeId: 5 },
{ mediumSizeUrl: 'ratilla.jpg', typeId: 12 }
];
const isUsable = media => media.typeId === MULTIMEDIA_IMAGE_TYPE_ID && media.mediumSizeUrl;
const images = multimedias.filter(isUsable).map(media => media.mediumSizeUrl)
console.log(images) // ["panda.jpg", "koala.jpg", "ratilla.jpg"]
const MULTIMEDIA_IMAGE_TYPE_ID = 12
const multimedias = [
{ mediumSizeUrl: 'dog.jpg', typeId: 2 },
{ mediumSizeUrl: 'panda.jpg', typeId: 12 },
{ mediumSizeUrl: 'koala.jpg', typeId: 12 },
{ mediumSizeUrl: 'trex.jpg', typeId: 5 },
{ mediumSizeUrl: 'ratilla.jpg', typeId: 12 }
];
const isUsable = media => media.typeId === MULTIMEDIA_IMAGE_TYPE_ID && media.mediumSizeUrl;
const images = multimedias.reduce((accumulator, media) => {
if (isUsable(media)) accumulator.push(media.mediumSizeUrl)
return accumulator;
}, [])
console.log(images) // ["panda.jpg", "koala.jpg", "ratilla.jpg"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment