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

Javascript : filter array of object remove all objects

I got a simple question, been hours on it and can’t figuring out the solution. I got an array of object. I want to remove the object that has same values that a variable I pass.

My problem is that it removes all the objects, even those that are not similar to my variable.

Here is my code

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

function appSelect(variable) {
    //we check if the object already exists in my array {id:x, value:y}
    const found = myArray.find(obj => {
        return (obj.id === variable.id && obj.value === variable.value);
    });
        
    if (found) { 
        //If find it, I want to remove it from my array

        const filtered = myArray.filter(obj => {
            return (obj.id !== variable.id && obj.value !== variable.value);
        })

    //Return empty array
}

I receive the value from a select form. For exemple I got myArray = [{id: 1, value: 12},{id: 2, value: 12},{id: 5, value: 12}] and variable = {id: 2, value: 12}

What I did wrong?

>Solution :

The reason is the code below:

return (obj.id !== variable.id && obj.value !== variable.value)

Which means if id or value is the same,then it will be filtered.

You can change it to

return !(obj.id === variable.id && obj.value === variable.value)

Full code:

function appSelect(variable) {
    //we check if the object already exists in my array {id:x, value:y}
    const found = myArray.find(obj => {
        return (obj.id === variable.id && obj.value === variable.value);
    });
        
    if (found) { 
        //If find it, I want to remove it from my array

        const filtered = myArray.filter(obj => {
            return !(obj.id === variable.id && obj.value === variable.value);
        })

    //Return empty array
}
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