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

Filter array problem inside React with multiple conditions

I’ve been trying to remove an item from my array for a while now but the filter removes too much.

My array:

[
    {
        "domain": "domain1.com",
        "slug": "monitor"
    },
    {
        "domain": "domain1.com",
        "slug": "monitor-1"
    },
    {
        "domain": "domain2.com",
        "slug": "monitor"
    }
]

I release the following filter

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

array.filter((item) => item.slug !== 'monitor')

This removed all my results exclude slug monitor-1, which is correct since I am asking the slug with monitor to remove.

Result:

[
    {
        "domain": "domain1.com",
        "slug": "monitor-1"
    },
]

But i only want to remove the slug monitor from domain1.com and not domain2.com

array.filter((item) => item.slug !== 'monitor' && item.domain !== 'domain1.com)

This will remove all the result so the array is empty

[]

How can I make it so that I get it like this, without deleting everything?
So only delete the domain: domain1.com with the slug: monitor.

[
    {
        "domain": "domain1.com",
        "slug": "monitor-1"
    },
    {
        "domain": "domain2.com",
        "slug": "monitor"
    }
]

>Solution :

You are almost correct,just need to change the expression in Array.filter(),below is a reference for you

let data = [
    {
        "domain": "domain1.com",
        "slug": "monitor"
    },
    {
        "domain": "domain1.com",
        "slug": "monitor-1"
    },
    {
        "domain": "domain2.com",
        "slug": "monitor"
    },
    {
        "domain": "domain2.com",
        "slug": "monitor-1"
    }
]

let result = data.filter(d => !(d.slug === 'monitor-1' && d.domain === 'domain1.com'))
console.log(result)
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