Created
October 7, 2016 17:47
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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