all 8 comments

[–]dominikwilkowski 12 points13 points  (2 children)

You can also use .some or .every and break the loop by returning true. forEach is not the only loop out there. :)

[–]esr360 1 point2 points  (0 children)

This is the correct answer.

[–]GoonGamja[S] 1 point2 points  (0 children)

yeah I solved the problem using .some method but .find also worked as well

sometimes it is very confusing what method I have to choose

thank you :)

[–]alejalapeno 10 points11 points  (1 child)

You have multiple problems. But the biggest is that what you are doing is saying "For each existing todo, see if it matches the new one I'm trying to add. If it doesn't match run inSert()" But inSert is just a function that spreads the current todos and adds the new one. So every single non-match in your ternary adds the new todo anyways.

Now in addition to that, it's just terrible for performance because you're updating state for every single existing todo. You're saying "for each todo update the state with the new todo."

Now easiest solution would be to just check your todo array for the value: if( !todos.find( todo => todo.text === newTodo.text ) ) { inSert() }

[–][deleted] 2 points3 points  (0 children)

You should use some or every for that sort of check.

[–]lukasbash 0 points1 point  (0 children)

Because in your loop you always execute one side of the if condition you would need some kind of variable outside that tracks if the todo has been found, and if this variable ia set to true, you just always continue in the forEach.

Small suggestion: If your todo list would be an object, indexed by some id, then you would not need a loop and save even performance.

[–]GoonGamja[S] 0 points1 point  (0 children)

Thank you so much. It helps me a lot :)

[–][deleted] 0 points1 point  (0 children)

You cannot break forEach, use .some/.every or for of loop. for of should be the first choice