0
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

Matthew Herbst
  • 29,477
  • 23
  • 85
  • 128
  • The only way `project.myTasks === children` returns true is if they are the same array. Not different arrays with identical elements. For example, calling the function with project1.myTasks as the parameter will match when the forEach is looping over project1, but not project2. – James Oct 12 '22 at 18:36
  • https://stackoverflow.com/a/14853974/20394 explains how to compare the contents of arrays. If you need to save the contents of an array to compare later, you can use `let copy = [...original]` – Mike Samuel Oct 12 '22 at 18:38

2 Answers2

1

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)

Matthew Herbst
  • 29,477
  • 23
  • 85
  • 128
  • the deal is that the code actually works, and my question was why it works as intended. Your method won't work since if many projects have the same array lengths then the wrong array is going to be deleted – Kamran Huseynov Oct 13 '22 at 08:47
0

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)
BehRouz
  • 1,209
  • 1
  • 8
  • 17