Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
156
rated 0 times [  163] [ 7]  / answers: 1 / hits: 34744  / 7 Years ago, tue, june 27, 2017, 12:00:00

I have a object containing the following:



assets = [
{ id: 1, type: 'image', url: 'image.jpg' },
{ id: 2, type: 'video', url: 'video.mp4' },
]


I'd like to filter based on user selection of IMAGE, VIDEO, or ALL.



I cannot think of a clean way to filter use for the ALL case.



currentOption = 'image'
assets.filter(asset => asset.type === currentOption)


This will work for IMAGE or VIDEO, but not ALL.



I could check in my filter function:



const currentOption = 'all'
const filterFunc = asset => {
if (currentOption == 'all') return true
return asset.type === currentOption
}
assets.filter(filterFunc)


But wouldn't it be better to short-circuit the filter to not iterate each item?



Edit:
To answer questions why not skip filter all together. I was trying to keep it framework agnostic. But this is rendered using react. So I would have to do something like:



<div>
{currentOption === 'all' ?
assets.map(asset =>
<img src={asset.url} />
)
:
assets.filter(asset => asset.type === currentOption).map(asset =>
<img src={asset.url} />
)
}
</div>


Plus this doesn't even account for the code to display a video. Basically I was trying to reduce duplication in the view code.


More From » filter

 Answers
12

You could use the ternary operator to decide whether or not to apply the filter:



currentOption === 'all' ? assets : assets.filter(asset => asset.type === currentOption)


The mapping to images, that you added to the end of your question, could be written like this:



(currentOption === 'all' ? assets : assets.filter(asset => asset.type === currentOption))
.map( asset => <img src={asset.url} /> )

[#57286] Saturday, June 24, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
brennonr

Total Points: 124
Total Questions: 101
Total Answers: 101

Location: Estonia
Member since Wed, Jun 8, 2022
2 Years ago
;