How can I remove elements of an array in a loop?

  • 0
    There is an array:
    tasks: [
                    {
                        title: 'Make todo list',
                        completed: true
                    },
                    {
                        title: 'Go skydiving',
                        completed: false
                    }
                ],

    there is a clear completed button that calls the function
    clearCompleted() {
    				
    				this.tasks.forEach((item,index)=>{
    					if(item.completed){
    						this.tasks.splice(index,1)
    					}
    				})
                }

    It seems that under this condition, at each iteration, the interpreter must check the if block and if true remove the current element by index from the array, but for some reason it is one, then two objects with the property completed: true are left on the board and only when clicked again removes them ... Where is the mistake?
    JavaScript Felix English, Nov 7, 2019

  • 3 Answers
  • 0
    You can do it like this. This method will completely replace the entire array, leaving only the elements with the completed property in it! == true

    clearCompleted() {
    this.tasks = this.tasks.filter(t => !t.completed)
    }
    Anonymous

  • 0
    for some reason, he sometimes one, then two objects with the property completed: true leaves on the board and deletes them only when they click again. Where is the mistake?


    You remove the elements of the array you are iterating over.
    Anonymous

  • 0
    What does the console say? Total log?



    It's not clear how you render the array.

    Perhaps your array is not reactive for some reason.
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!