Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.