Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript filter method, Remove all Items with matching values in array

I'm trying to remove all items if they match with array values but it's removing only one item. How can i remove all items with filter method or what is the best way to achieve this.

let data = [
    {
        id: '1',
        title: 'ABC'
    },
    {
        id: '2',
        title: 'DEF'
    },
    {
        id: '3',
        title: 'GHI'
    },
    {
        id: '4',
        title: 'JKL'
    },
    {
        id: '5',
        title: 'MNO'
    }
]


data = data.filter(post => {

    let remove = ['2', '4', '5']

    for(let i = 0; i < remove.length; i++) {
        return post.id !== remove[i]
    }

})

console.log(data)

Thanks

like image 279
Key Avatar asked Jan 18 '26 08:01

Key


1 Answers

you should return false if you want to remove item from array

let data = [
    {
        id: '1',
        title: 'ABC'
    },
    {
        id: '2',
        title: 'DEF'
    },
    {
        id: '3',
        title: 'GHI'
    },
    {
        id: '4',
        title: 'JKL'
    },
    {
        id: '5',
        title: 'MNO'
    }
]
let remove = ['2', '4', '5']

data = data.filter(post => {
return !remove.includes(post.id);
})

console.log(data)
like image 57
Ivan Karaman Avatar answered Jan 20 '26 00:01

Ivan Karaman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!