JavaScript's forEach() method does not iterate through every single item

I am a beginner in javascript and I'm trying to figure out how to remove all objects with the completed property set to true.

However, my current function is not achieving this. Can anyone help identify what I may be missing?

const tasks = [{
    title: 'task1',
    completed: true
},{
    title: 'task2',
    completed: true
},{
    title: 'task3',
    completed: true
},{
    title: 'task4',
    completed: true
}]

const removeCompletedTasks = function(tasks){
    tasks.forEach(function(task,index){      
        if(task.completed){            
            tasks.splice(index,1)        
        }
    })
}

removeCompletedTasks(tasks)
console.log(tasks)

Answer №1

If you prefer, you have the option to utilize Array.prototype.filter in this scenario:

const notDone = tasks.filter((task) => !task.completed)
const done = tasks.filter((task) => task.completed)

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

How can JavaScript be properly embedded using PhantomJS?

My objective is to insert the following code snippet into a website using PhantomJS: javascript document.getElementById("pickupZip").value = "90049"; document.getElementById("refreshStoresForZipPop").click(); After attempting this in my inject.js file, I ...

Create a personalized form with HTML and JQuery

Currently, the data is displayed on a page in the following format: AB123 | LHRLAX | J9 I7 C9 D9 A6 | -0655 0910 -------------------------------------------------------- CF1153 | LHRLAX | I7 J7 Z9 T9 V7 | -0910 1305 ---------------- ...

After making a POST request, the `Req.body` is assigned to

This is the JavaScript code I am using: app.use(express.static(__dirname)); app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); // support json encoded bodies app.get('/', function(req, res){ res.sendFile(__dirn ...

Text is misaligned with the cursor position

I've created an HTML file and implemented a typewriter-like animation using typed.js. Here's the code snippet: var typed = new Typed('#typed', { stringsElement: '#typed-strings', smartBackspace:true, ...

Creating an express route for updating with various parameters: a step-by-step guide

I am trying to make an update to a specific attribute in a JSON object by using the fetch PUT method. I have set up a put function that takes in 2 URL parameters app.put('/trustRoutes/:id/:item', (req, res){ So far, I have been able to update t ...

What is the best way to implement the 'setInterval' function in this code to effortlessly fetch forms or data on my webpage without any need for manual refresh?

I am using ajax and javascript to fetch a modal on another page or in a separate browser. While I am able to retrieve the modal, I require the page to refresh before displaying the modal. I have come across suggestions to use the setInterval function but I ...

Output the keycode to the console repeatedly

I'm currently facing a minor mental obstacle: I have a javascript function embedded in html that displays the keycode when a key is pressed. It's connected to a function that provides detailed information about the character and keycode being pre ...

Is it necessary to close the browser for jQuery to reload an XML document?

I've successfully used jQuery's $.ajax to retrieve an xml value in my code. However, I'm facing an issue where any changes made to the xml document are not reflected upon a browser refresh. Specifically, the new saved xml value xmlImagePath ...

How can I ensure that an array remains unchanged when it is passed to a method in Ruby?

My goal is to pass an array into a method and manipulate its values based on random numbers. The process involves selecting a value from xArray[i] and copying it into yArray[x], where the index x increments with each iteration. However, I am puzzled by th ...

Exploring the world of tweets using React

While trying to retrieve tweets using the Twit package, I keep encountering error 400. I received an error message stating: "Failed to load https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=twitterdev&count=10: Response to prefligh ...

Consolidate multiple generic items into a single entry

In my current project, I am structuring the types for a complex javascript module. One of the requirements is to handle multiple types using generics, as shown in the snippet below: export interface ModelState< FetchListPayload, FetchListR ...

Dynamically add a checkbox using JavaScript

Can anyone assist with dynamically setting a checkbox in JavaScript? function updateCheckboxValue(html){ var values = html.split(","); document.getElementById('fsystemName').value = values[0]; if (values[1] == "true"){ docume ...

Encountering an undefined value from state when implementing useEffect and useState

One issue I am facing is that the state of my projects sometimes returns as undefined. It's puzzling to me why this happens. In the useEffect hook, I have a function that fetches project data from an API call to the backend server. This should return ...

Start up a server using Angular along with Node.js and Express framework

I am encountering an issue with configuring Express as a server in my Angular application. The app loads without any issues when accessing the HOME route, but when trying to access another route, I receive an error message: Cannot GET / This is how I hav ...

Populate DataGrid using an input through AJAX and jQuery technology

I've been grappling with a persistent issue that's been bothering me for days now. Here's the scenario: Currently, I have a DataGrid that is empty and an Input Text field in place that utilizes AJAX and jQuery to display a list of available ...

Issue with using GET fetch request in JavaScript-ReactJS app

I'm currently attempting to make a basic GET request from my ReactJS application to a Node.js API. However, I am encountering a 304 status response instead of the desired 200 status. My goal is to store the response from the GET request in a variable. ...

Show image when hovering over individual words

Is there a way to display different descriptions or images when hovering over each word in a paragraph using HTML? It seems that only the last element is being retrieved and displayed across the entire paragraph. Any suggestions on how to fix this issue wo ...

"The ng-route feature is not working as expected; instead of displaying the template url, it is showing

I'm currently developing a voting application as part of my freecodecamp project using the MEAN stack. I have completed the backend portion, but without user authentication for now. My focus now is on the frontend. I have created an HTML page that li ...

Encountering a JavaScript glitch with Bootstrap 3 jQuery offset

I am facing an issue with a function that throws an error in the console of my browser when the page is loading: function getRight() { return ($(window).width() - ($('[data-toggle="popover"]').offset().left + $('[data-toggle="popover"]& ...

Is there a way to eliminate the black seam that is visible on my floor mesh that has been separated? I am utilizing A

I recently imported a large .glb file into AFrame. The model has baked textures and the floor is divided into multiple mesh parts for improved resolution. However, I am facing an issue where black seams appear on the separated parts of the floor, only dis ...