Nested loops seem to override previous results with the final output

I am attempting to iterate through an array of months nested within an array of 'years' in order to calculate a count for each month using a custom angular filter. Initially, I set up the structure I will be looping through in the first while loop.

while(i < itemYears.length) {
                // Exclude null end dates and combine year part of other end dates with months array.
                if (itemYears[i].end !== undefined && itemYears[i].end !== null) {
                    completeByMonth.push({ year: itemYears[i].end.substring(0,4), months: months });
                }
                i++; // Move to next iteration
            }

The structure created by the above loop is as follows:

 {
  year: 2015,
  months: [
   { number: '01', text: 'January', count: 0 }
    ...
    ...
  ]
}

In the nested while loop, I proceed to iterate through each month of every item.

        // Loop through the years
        while(j < completeByMonth.length) {
            var year = completeByMonth[j], k = 0;
            // Iterate through the months for the current year
            while(k < year.months.length) {
                year.months[k].count = $filter('endedMonth')(items, year.year, year.months[k].number).length; // Filter items based on year and month.
                console.log(year.year, year.months[k].text, 'count', year.months[k].count);
                k++; // Move to next month
            }
            console.log(year);
            j++; // Move to next year
        }

        console.log('completeByMonth', completeByMonth);
        return completeByMonth;

Although the console logs show the correct counts for each month of every year, the final output of the completeByMonth array displays identical month counts for each year, resembling those of the last year in the array.

Question: What strategies can I implement to prevent this issue of overwriting month counts?

I would greatly appreciate any advice or alternative approaches to tackle this challenge.

Answer №1

I don't have a clear understanding of the purpose of the filter in this context. However, I've modified your code using forEach within an Angular framework. Instead of using the filter, I've implemented an example count logic which I find more readable. Hopefully, this adjustment resolves the issue you are facing.

var i = 0;
angular.forEach(completeByMonth, function(year){
    angular.forEach(year.months, function(month){
        i++;
        month.count = i;  
    });
});

https://jsfiddle.net/HB7LU/15162/

Answer №2

Give this a try:


    while(l < monthlyTotal.length) {
        var century = monthlyTotal[l], m = 0;
        //loop through the months for each year.
        while(m < century.monthsCount.length) {
          (function(month, currentCentury){
            currentCentury.months[month].total = $filter('calculateMonth')(items, currentCentury.year, currentCentury.months[month].value).length; //filter items by year and month.
            console.log(currentCentury.year, currentCentury.months[month].label, 'total', currentCentury.months[month].total);
          )(m, century);
          m++; //move to next
        }
        console.log(century);
        l++; //move to next
    }

    console.log('monthlyTotal', monthlyTotal);
    return monthlyTotal;

The issue you are experiencing is not specific to Angular, but rather how JavaScript handles variables. For more information on this topic, check out https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures (specifically the section on "Creating closures in loops: A common mistake").

Answer №3

Issue resolved! I streamlined the process by combining object creation and count calculation into one step:

  1. Create the object and calculate the counts simultaneously.

Although the code may not be aesthetically pleasing, it now delivers accurate results for all years.

while(i--) {
            //Include only relevant end dates in the array with corresponding month counts.
            if (itemYears[i].end !== undefined && itemYears[i].end !== null) {
                completeByMonth.push({ year: itemYears[i].end.substring(0,4),
                                      months: [
            { number: '01', text: 'January', count: $filter('endedMonth')(items, itemYears[i].end.substring(0,4), '01').length  },
            { number: '02', text: 'February', count: $filter('endedMonth')(items, itemYears[i].end.substring(0,4), '02').length },
            { number: '03', text: 'March', count: $filter('endedMonth')(items, itemYears[i].end.substring(0,4), '03').length },
            { number: '04', text: 'April', count: $filter('endedMonth')(items, itemYears[i].end.substring(0,4), '04').length },
            { number: '05', text: 'May', count: $filter('endedMonth')(items, itemYears[i].end.substring(0,4), '05').length },
            { number: '06', text: 'June', count: $filter('endedMonth')(items, itemYears[i].end.substring(0,4), '06').length },
            { number: '07', text: 'July', count: $filter('endedMonth')(items, itemYears[i].end.substring(0,4), '07').length },
            { number: '08', text: 'August', count: $filter('endedMonth')(items, itemYears[i].end.substring(0,4), '08').length },
            { number: '09', text: 'September', count: $filter('endedMonth')(items, itemYears[i].end.substring(0,4), '09').length },
            { number: '10', text: 'October', count: $filter('endedMonth')(items, itemYears[i].end.substring(0,4), '10').length },
            { number: '11', text: 'November', count: $filter('endedMonth')(items, itemYears[i].end.substring(0,4), '11').length },
            { number: '12', text: 'December', count: $filter('endedMonth')(items, itemYears[i].end.substring(0,4), '12').length }
        ] });
            }
        }

Appreciate all the helpful responses!

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

Instructions for implementing tooltips on a pie chart slice when hovering with the mouse pointer, using the canvas

var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var cw = canvas.width; var ch = canvas.height; ctx.lineWidth = 2; ctx.font = '14px verdana'; var PI2 = Math.PI * 2; var myColor = ["Gr ...

What is the best way to access a value within a JSON object in a React render method?

Overview I am currently working on creating a blog using React and JSON data. Upon checking this.state.blogs, I am getting the output of: [object Object],[object Object],[object Object]. I have attempted to use the .map function but I am not sure how to ...

Issue with smart table sorting functionality

I've been working on a table with just one column that is populated from a string array. However, I'm struggling to get the sorting functionality to work properly. Can anyone pinpoint what mistake I might be making here? Steps taken so far: 1) ...

Struggling to retrieve a JSON object from an Express and Node application, only receiving an empty result

Can anyone assist me? I'm having trouble with the res.json() function in my code. It seems to work after the first request, but not after the second. Right now, my application is quite simple - it scrapes user data from social media platforms like Twi ...

"An unexpected compilation error (800A03EA) has occurred in the JavaScript syntax during

My computer is facing a frustrating compilation issue with JScript and node. Despite trying various solutions found online, the problem persists. After navigating to CD>PROJECT: npm init successful npm install -g globally and locally installed correct ...

Develop a plugin architecture using JavaScript and Node.js

Here is a basic implementation using node.js with express: var express = require('express'); var app = express(); app.get('/', function(req, res){ res.send('Hello World'); }); app.listen(3000); I am interested in creatin ...

What's the best way to vertically center a div with a 100% width and a set padding-bottom on the screen?

I am struggling with positioning the following div on my webpage. .div { width:100%; padding-bottom:20%; background-color:blue; } <div class="div"></div> I have been searching for a solution to vertically center this responsive div on my web ...

Locate a specific option that matches the value of the selected data-status and set it as "selected" using jQuery

Currently, I am facing an issue where I need to load 2 separate ajax responses into a select dropdown. The select dropdown will have a data-status attribute, and my goal is to loop through the options to find the one that matches the value of the select da ...

Expanding cards with Material-UI and React seems to be a challenge when using an expander

I've recently integrated a Card component into my project, sourced from material-ui's official website. However, I'm encountering an issue where the CardHeader does not expand upon clicking. This is the structure of my Component : import ...

Inspect the json data to find a specific value and then determine the corresponding key associated with

I am currently working with JSON data retrieved from which I am storing in a variable. Despite my limited experience with JSON/JS, I have been unable to find a solution through online searches. Here is the code snippet: function checkMojang() { var moj ...

I am looking to utilize React and Next.js to map my array from an object. The component is a function employing hooks

I am attempting to map an array within an object and encountering some challenges. The structure of the object is as follows: const data = {data: (6) [{…}, {…}, {…}, {…}, {…}, {…}], page: 2, per_page: 6, total: 12, total_pages: 2} I have been ...

Receiving a blank array from the firestore database

I have written a code for the LeftBar Component where I am trying to retrieve data stored in the "contacts" document in Firebase. However, I am getting an empty array and I'm not sure why this is happening. Additionally, I would like to know how to ac ...

Merge arrays values with Object.assign function

I have a function that returns an object where the keys are strings and the values are arrays of strings: {"myType1": ["123"]} What I want to do is merge all the results it's returning. For example, if I have: {"myType1": ["123"]} {"myType2": ["45 ...

Discover the process of loading one controller from another controller in Angular JS

Is it possible to load an entire controller1 from a different controller2, not just a function? ...

Setting up a Node.js application with Nginx on DigitalOcean

While running my application on a DigitalOcean droplet using nginx, I encountered a peculiar issue. The app runs perfectly fine with http, but when switching to https, nginx throws a 502 BAD GATEWAY error. Despite trying various DigitalOcean guides and sco ...

What is the method for retrieving the name of the currently selected HTML element?

After using jQuery to select certain tags, I am now trying to obtain the name of each tag: $('select, :checkbox, :radio').each(function(){ // ... }); To accomplish this, I have attempted the following code: $('select, :checkbox, :radio ...

Start Your Sentences with an Exclamation Point using an AngularJS Filter

When working with AngularJS, I encountered an issue while filtering a list of objects using ng-repeat: <tr ng-repeat="application in page.applications | filter: {DisplayName:page.ApplicationSearchValue}"> {{application.DisplayName}} </tr> ...

Methods for breaking down a number into individual elements within an array

Suppose there is a number given: let num = 969 The goal is to separate this number into an array of digits. The first two techniques fail, but the third one succeeds. What makes the third method different from the first two? num + ''.split(&ap ...

Is there a way to customize the pagination dots in react-native-swiper-flatlist?

Is it possible to customize the pagination dots style for react-native-swiper-flatlist? <View style={styles.container}> <SwiperFlatList autoplay={false} autoplayLoop={false} index={0} showPagination ...

Using LocalStorage in Greasemonkey

I am currently working on developing a Greasemonkey script, but I am encountering difficulties with implementing local storage within it. The method I found to work with local storage in Greasemonkey involves creating another instance of JavaScript using t ...