Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Filtering out an array for only images

So i have an array that has many file types. These are all under array.contentType. What i want, is to just have it return images, so array.contentType.images? i think.

Here is the code:

    const renderSlides = attachmentInfo.map((item,index) => (
        <div key={index}>
            {item.contentType === 'image/jpeg' ? <img src={item.url} /> : ''}
            <p className="legend">{item.name}</p>
        </div>
    ));

My guess is i need to change the .map to .filter, but i’ve never used .filter. And from what i’ve read online its a bit confusing. The ternary works, but it returns a blank screen in my carousel slide for everything that isn’t an image. What i want is JUST the images.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Array.filter produces a new array where items match the predicate (function returning a boolean) provided.

For example:

console.log([-1, 0, 1, 2, 3].filter(x => x >= 1));

would result in the value:

[1, 2, 3]

A filter method call will have to be placed in front of the call to the map method. Additionally, all images have a content type starting with "image/", so checking for images can be generalized as well. Putting these both together would result in the following code:

    const renderSlides = attachmentInfo.filter(({contentType}) =>
        contentType.startsWith('image/')
    ).map((item,index) =>
        <div key={index}>
            <img src={item.url} />
            <p className="legend">{item.name}</p>
        </div>
    );
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading