Home > Blockchain >  Why the equality works as intended?
Why the equality works as intended?

Time:10-13

const removeProject = (children) => {
    UI.myProjects.forEach(project => {
        if (project.myTasks === children) {
            UI.myProjects.splice(UI.myProjects.indexOf(project), 1)
        }
    });
}

Context:

I have a project factory which creates it's own array of tasks called myTasks . At the start each one of them is empty

UI.myProjects is an array which holds all the projects

when this function fires it iterates over all the projects and their myTasks to find the one that is equal to children(a myTasks array of a project that needs to be deleted)

so my question is: When I create a bunch of projects with empty myTasks arrays with children array also being empty, why the function deletes only the project which I want to delete and not the other project which has exactly the same array as the other empty project.

to clarify:

UI.myProjects = [
random project 1{ myTasks = [] },
random project 2{ myTasks = [] },
random project 3{ myTasks = [bla bla]},
the project that I want to delete{ myTasks = []}
]

function fires : deletes the right project and does not affect 1st and 2nd projects.

I think it's because it somehow checks if the parent of that array also matches, and if it does then how does it do that if I am only passing an array and not the whole project

CodePudding user response:

You are using ===, which does strict equality checking, to compare arrays. Every array is technically its own object. No two arrays will ever be equal to each other, even if their content is the same.

[] === [] // false

You should instead be checking the values within the array. You could add a short-circuit and say if (project.myTasks.length === 0 && children.length === 0)

CodePudding user response:

In javascript [] === [] or [] == [] will return false, no matter what's inside those arrays. There are other ways to compare two arrays:

JSON.stringify(a) === JSON.stringify(b)
  • Related