Is there a way to clear all completed tasks automatically when a function is called?

I am currently developing in Angular and facing an issue with checkboxes that toggle a Boolean value to denote task completion. I have two arrays - one containing a list of objects and the other storing the first key values upon completion and clearance.

$scope.taskList = [{
  complete: false,
  foo: "1",
  bar: "2",
  baz: "3"
}];

$scope.completedTasks = [];

Although my function effectively clears tasks when one or two are selected, it struggles as the number of checked items increases. Only a fraction of the checked items get cleared at once, while invoking the function multiple times eventually clears all tasks individually. However, I am unable to figure out a way to clear the entire list in a single go.

$scope.clearComplete = function() {
  for (var i = 0; i < $scope.taskList.length; i++) {
    if ($scope.taskList[i].complete == true) {
      $scope.completedTasks.push($scope.taskList[i].foo);
      $scope.taskList.splice(i, 1);
    }
  }
  console.log($scope.completedTasks);
  return $scope.taskList;
};

I am struggling to correct the logic and would greatly appreciate any fresh perspectives on how to resolve this issue.

For this particular project, I aim to minimize dependencies and do not want to rely on external helper libraries like Underscore and Lodash.

Answer №1

If you find yourself using taskList.splic, consider looping in reverse order for improved efficiency. Alternatively, you can achieve the same result with a cleaner approach like this:

var incompleteTasks = [];
$scope.tasks.forEach(function(task){
    if(task.complete) {
        $scope.completedTasks.push(task.foo);
    } else {
        incompleteTasks.push(task);
    }
});
$scope.tasks = incompleteTasks;

By following this method, you only need to iterate through your array once, resulting in a more streamlined process.

Answer №2

No external libraries are required to utilize forEach or filter. To maintain readability, I suggest breaking the process into two distinct steps:

$scope.clearCompletedTasks = function() {

  // Move completed tasks to a separate array
  $scope.taskList.forEach(function(task) {
    if(task.completed) {
      $scope.completedTasks.push(task.id);
    }
  });

  // Filter out completed tasks from the original list
  $scope.taskList = $scope.taskList.filter(function(task) {
    return !task.completed;
  });

  console.log($scope.completedTasks);
  return $scope.taskList;
};

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

Transform Json data into CSV file format with customized headers and formatting

I have a function in my code that fetches JSON data from an endpoint and converts it into a CSV file. Is there a way for me to specify specific headers and the order of columns I want in this CSV file? function downloadJSONAsCSV(endpoint) { // Fetch J ...

Injecting styles dynamically into an Angular component enhances its appearance and functionality

I am in need of help with styling a component using CSS styles specified by an object of selectors to CSS properties. Check out my sandbox here: https://codesandbox.io/s/happy-goldberg-4740z Here are the styles to be applied from the parent: const styles ...

Explain the inner workings of the setTimeout() function in JavaScript

My goal is to create a line in my code by placing points according to the line equation and adding a 100 millisecond delay before each point is displayed. However, when I try to run the code, it seems to wait for some time and then displays all the points ...

Contrast 2 GET objects retrieved from separate controllers

I have 2 collections of data from different controllers. Data Collection 1 (Controller Name): [{id:1,"name":"jakov"},...] Data Collection 2 (Controller Nickname): [{id:1, "nickname" : "jandric", "nameId" :1, "title" : "master"},...] I send data from C ...

Adjust the size of an event in the Angular Full Calendar with Chronofy, while utilizing constraints to control the drag and drop functionality

I'm currently in the process of developing an availability calendar for scheduling meetings during open times. If a time slot is unavailable, users should not be able to place an event there. While I have successfully implemented this feature, I am ...

Configuring servers for contemporary JavaScript applications

In search of a solution that would enable server settings to be stored in a separate config file from the JS application, allowing for flexibility between development and production modes. The goal is to have the server replace the config file with an upda ...

Setting up jade includes with gulp-jade: A comprehensive guide

Struggling with setting up Jade includes in your gulpfile.js while using gulp-jade? Check out this link for more information. Below is a snippet from the gulpfile.js: var gulp = require('gulp'); var browserSync = require('browser-s ...

Error: Attempting to modify the 'chat_room_id' property of an undefined object results in a TypeError when ng-if is used

Currently facing a roadblock in my project. I am developing a chat feature that is located within a Rails partial in the application.html.erb file. The goal is to have a user's list of friends displayed in the chat area initially. When a user clicks ...

JavaScript accordions failing to open

I've encountered an issue with my website that includes JS accordions. Strangely, they are not opening on the live site, but they function properly on Codepen. I checked the console in Chrome and found no error messages, however, when I looked at the ...

Storing the model using three.js

Is it feasible to store models created in three.js into a database and later retrieve them, rather than just using the save tab? ...

I'm curious about how to retrieve the file path within a Meteor package

Can someone please guide me on how to obtain the path of a specific file within my Meteor project, as I am already familiar with obtaining the current directory from a Meteor package. I have tried using node's __dirname and __filename, but they do no ...

Using Vue along with bootstrap-vue: Ensuring only one list element is expanded in a list (v-for) at any given time

In my Vue project with bootstrap-vue, I am utilizing the b-collapse feature within a v-for loop for lists. While it is functioning correctly, I am struggling to automatically close expanded list elements when a new one is clicked. Here is my question: Ho ...

When you click away from the div in AngularJS, it will automatically disappear

Whenever we click outside the div or in a window, the xyz should be hidden. const app = angular.module('myApp', []); app.controller('myCtrl', function($scope) { $scope.showDropdown = false; $scope.helloClick = funct ...

BS Modal was improperly invoked, leading to an illegal instantiation

Currently, I am attempting to trigger a bootstrap Modal in Angular by utilizing the component instead of its HTML attribute. However, I am encountering an error (specifically, illegal invocation). Here is the code snippet from the component: @ViewChild(&a ...

A guide to parsing JSON files and extracting information

How can I extract the name and status from a JSON object? I've attempted various methods like [0] - [1], as well as trying without, but to no avail. [ { "status": "OK" }, { "id": "1" ...

Leverage nearby data using MediaSource

I am currently working on creating a local video player using nwjs (node-webkit). I have successfully played local files by setting their path as the src attribute of the video element. Now, I want to explore using MediaSource and potentially URL.createObj ...

Encountering issues with Angular UI router when attempting to resolve multiple dependencies

Currently, I am utilizing AngularJS version 1.6.10 along with angular-ui-router version 1.0.18, but this combination is resulting in the following error: [$injector:unpr] Unknown provider: dashboardDataProvider <- dashboardData <- dashBoardCtrl In ...

Combining multiple data sources into a single input field in VueJs

I've been exploring the idea of incorporating multiple values into a vue form input binding Here's an example snippet of my code. <template> <div> <label for=""> Employee </label> <input class="form-contro ...

Transitioning Web Application to Angular Version 2

I am currently in the process of transitioning a web application to Angular2. I have successfully transferred the HTML and CSS files to Angular's component.html and component.css respectively. However, I am encountering some difficulties with the .js ...

Manipulating input values on-the-fly with Reactjs

In my UserLists component, users can input values that are then displayed at the bottom of the screen. Each input value is stored in the whitelist state and mapped to create additional inputs for editing or deleting. I am facing issues with deleting the ...