Count the number of times an iteration occurs in AngularJS/JavaScript

I need assistance with my code snippet below, as I am trying to determine the count of all instances where $scope.rm is equal to "failed" or when $scope.percentage is less than 50.

angular.forEach(result1, function (value, key) {

    $scope.percentage = (value.score * 100 / value.total).toFixed(2);

    if ($scope.percentage < 50) {
        $scope.rm = "Failed"
        $rootScope.sendmail = 0

    }else {
        $scope.rm = "Passed"
        $rootScope.sendmail = 1
    }

});

Answer №1

Initiate a counter variable outside of the forEach loop and set it to zero

Increment the counter when you encounter $scope.rm = "Failed"

This will give you the number of times the loop runs for that condition

For example:

var Failedcount=0, Passedcount=0;
angular.forEach(result1, function (value, key) {

       $scope.percentage = (value.score * 100 / value.total).toFixed(2);

                    if ($scope.percentage < 50) {
                        $scope.rm = "Failed"
                        $rootScope.sendmail = 0
                        Failedcount++;

                    }else {
                        $scope.rm = "Passed"
                        $rootScope.sendmail = 1
                        Passedcount++;
                    }

                });
console.log("failed counter",Failedcount)
console.log("passed counter",Passedcount)

Answer №2

let countFailed = 0;

angular.forEach(result1, function (value, key) {
  $scope.percentComplete = (value.score * 100 / value.total).toFixed(2);  

  if ($scope.percentComplete < 50) {
     $scope.status = "Failed"
     $rootScope.sendEmail = 0
     countFailed++;
  }else {
     $scope.status = "Passed"
     $rootScope.sendEmail = 1
  }
});

console.log('Total number of failed tests: '+countFailed);

Answer №3

In this code snippet, a new variable is introduced to keep track of the number of failures.

$scope.numberOfFails = 0

The variable will increment by 1 whenever the fail condition is satisfied, effectively counting each occurrence of failure.

$scope.numberOfFails = 0
angular.forEach(result1, function(value, key) {

  $scope.percentage = (value.score * 100 / value.total).toFixed(2);

  if ($scope.percentage < 50) {
    $scope.rm = "Failed"
    $rootScope.sendmail = 0
    $scope.numberOfFails++
  } else {
    $scope.rm = "Passed"
    $rootScope.sendmail = 1
  }

});
console.log($scope.numberOfFails)

Upon execution, the variable $scope.numberOfFails will accurately reflect the total number of failures.

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

Choosing between exclusive choices across multiple selection elements in Vue 3

In my Vue component, there are 5 distinct values stored in the options variable. I want users to select only one value from each of the 5 select options I provide. This means that once a user selects a value in one input select component, that same value c ...

Importing WebAssembly dynamically can sometimes lead to complications with the order of execution

I am attempting to load a WASM library from another node js application, both utilizing webpack. Within the WASM library, I have the following code snippet exporting the functionality. export default import("./pkg") .then(s => { le ...

There seems to be an issue with d3js bar charts as they are not displaying on the screen and there

Recently, I started delving into the world of D3js and decided to try my hand at creating some bar charts. However, despite my efforts, the bar charts failed to display on the screen. <!DOCTYPE HTML> <html> <head> <title> My D3 Pra ...

Using JSON data to populate an HTML page

I'm currently working on a project that involves creating a "Twitter" page. The idea is to utilize the JSON file available at to display some of its content. However, I'm facing an issue where my page only shows the table headers and nothing els ...

I'm looking to add autocomplete functionality to a text input in my project, and then retrieve and display data from a MySQL database using

Looking to enhance user experience on my form where users can select inputs. Specifically, I want to implement a feature where as the user starts typing in a text input field with data from a MYSQL database, suggestions will be displayed. The form is locat ...

Application experiencing server error when updating MongoDB data

I have encountered an issue while trying to update/modify data that has already been uploaded in a reactjs project using mongoDB as the database. Whenever I attempt to update the data, an error is displayed. How can this problem be resolved? https://i.sta ...

Struggling with Vue's Router Transition fade in/out effect not functioning as expected?

Question: I've implemented Vue's Router and it switches between components without any issues. However, I added a <transition name="fade" mode="out=in"> around it but the fade effect is not working as expected. Desired ...

Manipulating the DOM by nesting an icon within a button element in HTML

Currently working on my todo list project and I have a question about using innerHTML. I'm curious if I can include an icon inside of a button tag like this: btn.innerHTML = '<i class="fas fa-times fa-lg"></i>'; So, wo ...

New React Component Successfully Imported but Fails to Render

I've encountered issues with the code I'm currently working on. Dependencies: React, Redux, Eslinter, PropTypes, BreadCrumb Within a view page, I am importing components from other files. The current structure is as follows: import Component ...

Setting up Socket.io results in numerous transport polling GET requests being initiated

I have set up an express.js server-side and followed the socket.io guide. However, I am facing issues with the socket connection not being successful, and there seems to be a high number of unexpected GET requests like this: https://i.stack.imgur.com/GDGg ...

Tips for Automatically Loading Dependencies in AngularJS

Currently, I am working on an Angular application where I am designing various widgets using HTML5. Here is a snippet of the code structure: <html ng-app> <div ng-controller="widget1"> </div> <div ng-controller="widget2"> ...

"Exploring React Apex Chart Manipulation with Data, Images, and APIs

Is it possible to customize series and options in order to create a treemap chart using react hooks similar to this example? https://i.stack.imgur.com/NexH8.jpg The API includes data for name, user, and percent. { "data": [ { ...

The state update is triggering a soft refresh of the page within Next.js

In my Next.js project, I have integrated a modal component using Radix UI that includes two-way bound inputs with state management. The issue arises when any state is updated, triggering a page-wide re-render and refreshing all states. Here is a snippet of ...

Creating a custom navigation bar that elegantly fades away with a smooth animation as you scroll down the page is a must-have

How can I create a navigation bar that disappears when scrolling, with a smooth animation? This is the progress I have made so far. HTML: <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="css/style.css" type="tex ...

Stopping XSS Attacks in Express.js by Disabling Script Execution from POST Requests

Just starting to learn ExpressJs. I have a query regarding executing posted javascript app.get('/nothing/:code', function(req, res) { var code = req.params.code; res.send(code) }); When I POST a javascript tag, it ends up getting execut ...

Instantly summing up two numbers with javascript

In my web development work using Visual Studio 2008, I encountered an interesting challenge. On a webpage, I have three textboxes labeled "Price," "Quantity," and "Amount." The task at hand is to calculate the value of "Amount" by multiplying the values ...

Display the value of an array based on the current position of another array in AngularJS

When working with javascript, there are two arrays that have equal lengths that are determined by a database value which is unknown. For example: colName=['col1','col2','col3']; fieldValue=['abc','def',&apo ...

I'm struggling with developing react applications due to problems with canvas elements

I am currently using an M1 MacBook Pro, with Node version 15.4.1 and npm version 7.0.15. When I ran the command npx create-react-app my-app, it gave me this output: I have attempted various solutions but keep encountering the same issue related to "canva ...

Deliver data in batches of ten when the endpoint is accessed

I am currently in the process of developing a web application using Next.JS and Node. As part of this project, I have created my own API with Node that is being requested by Next.JS. One particular endpoint within my API sends data to the front end as an ...

What is the best way to access a promise's value in global scope within a reactjs application?

Currently tackling user authentication using web tokens in react. My approach involves utilizing the fetch() method to send a POST request to my backend, facilitating CORS. The issue arises when attempting to employ the setToken() hook within the .then() b ...