The Vue JS task manager is unable to remove completed tasks from the list

I'm encountering an issue with the 'DELETE ONLY FINISHED' button. The goal is for this button to delete all finished tasks. When a task is completed, its 'finishedTask' property changes to true. I have attempted to store all finished tasks in an array named 'finished'. However, I am unable to delete them all at once from that array. I tried using two nested for loops to address this problem, but unfortunately, it did not yield the desired results. Below is the complete code implemented in Vue.js. JSFiddle GitHub

new Vue({
  el: '#app',
  data: {
    index: 0,
    finished: [],
    todos: [],
    newTask: "",
  },
  methods: {
    addTask() {
      todo = {
        index: this.index++,
        task: this.newTask,
        finishedTask: false
      }
      if (this.newTask == '') {
        alert('Write a task!')
      }
      else {
        this.todos.push(todo);
        this.newTask = "";
      }
    },
    delete: function(index) {
      this.todos.splice(index, 1)
    },
    deleteEverything: function() {
      if (this.todos.length == 0)
        alert('You dont have tasks!')
      else
        this.todos.splice(0, this.todos.length)
        this.newTask = ""
    },
    finish: function(index) {
      this.todos[index].finishedTask = !this.todos[index].finishedTask
    },
    finishEverything: function() {
      for (var i = 0; i < this.todos.length; i++)
        this.todos[i].finishedTask = true
    },
    deleteFinished: function() {
      for (var i = 0; i < this.todos.length; i++) {
        if (this.todos[i].finishedTask == true) {
          this.finished.push(this.todos[i].index)

        }
          for (var j = 0; j < this.finished.length; j++) {
               this.todos.splice(this.finished[j], 1)

             }
       }

Answer №1

Instead of creating new arrays like completedTasks, you can utilize the filter method:

removeCompleted() {
    this.tasks = this.tasks.filter(task => !task.completed)
}

In fact, much of your code could be simplified - you could use map to mark all tasks as completed without having to iterate through the array.

Check out this JSFiddle for a demonstration: http://jsfiddle.net/xyz12345/20

Answer №2

In order to eliminate completed todos from the todos array, you can reassign it as follows:

removeCompletedTasks: function() {
  let inProgress = []
  this.todos.forEach(task => {
    if(!task.isCompleted) {
      inProgress.push(task)
    }
  })
  return this.todos = inProgress
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

jPlayer calculates the "duration" as 1,440 minutes on iOs devices for all mp3 files

My homemade webpage is designed for playing mp3s and viewing pdfs. I'm using jPlayer v 2.9.2 to play the mp3s, which works fine on PC but encounters issues on iPhone. The duration values are incorrect, showing "1439:59" remaining for all files, causin ...

I am encountering an issue with a JS addition operator while working with node.js and fs library

I'm trying to modify my code so that when it adds 1 to certain numbers, the result is always double the original number. For example, adding 1 to 1 should give me 11, not 2. fs.readFile(`${dir}/warns/${mentioned.id}.txt`, 'utf8', ...

Best practices for managing data loading with composition API and onBeforeRouteUpdate

I have a Vue 3 single-page component that contains the following script: export default defineComponent({ props: { id: String, }, setup(props) { const error = ref<boolean>(false) const thisCategory = ref<CategoryDetails>() ...

Retrieve the content of the nearest 'td' element using the '.closest()' method, then locate the desired

I am struggling to assign the value from a <td> to a variable. My approach involves utilizing the closest() and find() methods in jQuery to locate the desired <td>. Interestingly, when I use alert on the <td>, it displays the correct val ...

The function fs.createReadStream does not exist

Snippet to Submit Career Form: import axios from 'axios'; import FormData from 'form-data'; var fs = require('fs'); submitCareerForm(e){ e.preventDefault(); let formData = new FormData(); //formdata obje ...

Adding flair to the encompassing container

Below is the HTML code that I am working with: <div class="um-field field-date"> <p class="form-row " id="date_field"> <label class="date"> <input data-label="Date" data-value="" type="date" class="input-date um-frontend-f ...

adjust time in jQuery AJAX request when a button is clicked

I have the following code snippet that triggers when a button is clicked. When a user clicks on a button, I want to show a progress bar or waiting image in the browser for 5 seconds. How can I set a timeout and display the progress bar or waiting image wh ...

Incorporating JavaScript code within a partial response retrieved via AJAX

Is it frowned upon to include JavaScript within partials fetched via AJAX? Let's imagine a scenario where I have a button on that retrieves a form using AJAX. It is also desired to implement some jQuery event handlers for this form (such as validati ...

How can JSON data be passed to the Google Charts API?

I am currently working on a project that involves retrieving JSON data from a website and visualizing it on a live graph using the Google Charts API. Despite my efforts, I am unable to get the chart to display properly. Can someone please guide me in the r ...

Use jQuery to apply a class to some input elements when certain events like keyup or

If I type something in the input field, it should add a border to the li tag containing the text. The current script works fine, but is there a way to make this jQuery script shorter? Thank you for your help! .add_border{ border: 2px solid #000 !impor ...

One way to incorporate if / else if statements into a function within a Class component is by using conditional logic in React alongside Node and Express

I'm looking to refactor my code and extract the if/else if statements for error handling out of the component. How can I export this logic to another file and then import it back into my main component? Here's an example of the code: // PASSWOR ...

Automated library that refreshes the webpage instantly upon any server modifications

Seeking a Javascript solution to automatically refresh a webpage when the server version is updated. Update: I am aware of the technical aspects involved and how to implement this feature. However, I am interested in finding an existing solution that I ca ...

Develop a JSON parsing function for VUE reusability

Currently, I am iterating through an array in Vue that contains objects with strings nested within. These objects have various properties such as idType, type, user, visibility, seller, product, company, and additionalData. notifications: [ 0: { idTy ...

I am unsure about how to properly implement the reduce function

I am struggling with implementing the reduce function in my code. I have data output from a map function that consists of two documents. For example, one document contains: key "_id":"AD" "values" { "numtweets" : 1, "hastags" : ...

Verify the existence of the email address, and if it is valid, redirect the user to the dashboard page

Here is the code snippet from my dashboard's page.jsx 'use client' import { useSession } from 'next-auth/react' import { redirect } from 'next/navigation' import { getUserByEmail } from '@/utils/user' export d ...

Exploring click event beyond React Component: Jest + Enzyme Testing

I am looking to create a Jest and Enzyme test for a component that includes an event listener. The purpose of the test is to ensure that when a mousedown event occurs outside of a specific HTML element, a change is triggered (for example, toggling a state ...

Encountered an issue while attempting to decode the downloaded font. Parsing error from OTS in Vue

I'm facing an issue with importing a web-font into a specific component in my Vue App (built using the Vue cli webpack template). In one of my components, I attempted to import the fonts by referencing a _fonts.scss file within the project that looks ...

How to retrieve the clicked value using jQuery within a jinja2 loop

I'm currently working on an app that utilizes a Flask backend and Jinja2 templating. Within the HTML, I have a loop set up to organize data into batches, creating three columns on the web page: {% for batch in df.iterrows() | batch(3) %} <d ...

Creating unsightly class names using Node.js

Is it possible to automatically create random and unattractive class names? For example, is there a tool or plugin that can substitute the .top-header class with something like .a9ev within my CSS code? It would also be ideal if the class name in the HTML ...

Parsing XML to JSON using JavaScript

I came across this JavaScript function on Stack Overflow that I've been using to convert XML to JSON: function xmlToJson(xml) { try { var obj = {}; if (xml.nodeType == 1) { if (xml.attributes.length > 0) { ...