In JavaScript, there is a missing piece of logic when iterating through an array to find

I am working on a solution to populate empty values when data is not available for specific months. You can view my progress on Plunker here: http://plnkr.co/edit/f0IklkUfX8tkRZrn2enx?p=preview

$scope.year = [
{"month":"mar", "val":"23"},
{"month":"feb", "val":"45"},
{"month":"jan", "val":"56"}   
];

var total = ["jan", "feb", "mar", "apr", "may", "jun", "aug", "sep", "oct", "nov", "dec"];


for(var i=0; i<total.length; i++){

if($scope.year[i].month === undefined){ //Implement logic to identify missing month.

        $scope.year.push(
        {
            "month":total[i],
            "val":"0" 
        })
    }
}

I've created an array of default total months items to compare each month with the expected object. If a month is missing in the expected object, I need to add an empty item or set its value to "0" directly in the expected object.

Answer №1

Here's a potential solution you could try

Update with JavaScript

var year = [
{"month":"mar", "val":"23"},
{"month":"feb", "val":"45"},
{"month":"jan", "val":"56"}   
];

var total = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];


// Array for current months
var currentMonth = [];
angular.forEach(year, function(item){
currentMonth.push(item.month); 
});

// Iterate through months
for(var i=0; i<total.length; i++){
  //$scope.year = [];

// Check if month is missing
if(currentMonth.indexOf(total[i]) === -1){ //logic here to see absent month.

        year.push(
        {
            "month":total[i],
            "val":"0",
            "order" : i
        })
    } else {
     year[currentMonth.indexOf(total[i])].order = i;    // add order
}
} 

$scope.year = year;

HTML Markup

 <!-- Order by new property order -->
 <td ng-repeat="item in year | orderBy: 'order'">
            {{item.val}}
          </td>

Here is the link for further reference

Answer №2

The value of year[i] is not defined, hence attempting to access a property of a non-existent object. You can rectify this by adding the condition "if($scope.year[i] === undefined)"

Answer №3

Your approach of utilizing the orderBy function may not be suitable for sorting by month since it is not an alphabetical sort.

The following code snippet generates an array containing all the months present in the data. It then iterates over each month in a year, adding any missing data and eventually sorts the information based on the indexing of the months.

 // create array of available months
  var availableMonths = $scope.year.map(function(item){
    return item.month;
  });

  // loop through each month and add if missing from data
  total.forEach(function(mo){        
    if(availableMonths.indexOf(mo) ===-1 ){
      $scope.year.push({"month":mo, "val":"0" })
    }
  });

  // sort data using index of months
  $scope.year.sort(function(a,b){
    return total.indexOf(a.month) > total.indexOf(b.month);
  });

It's advised to remove the orderBy filter from the HTML as the data has already been sorted.

In fact, steps 2 & 3 above could be combined into a single operation using splice() to ensure the final order is accurate. However, I kept them separate here for clarity purposes.

DEMO

Answer №4

Give this a shot.

$scope.monthlyData = [

{"month":"jan", "value":"56"},
{"month":"feb", "value":"45"},
{"month":"mar", "value":"23"}

];

var allMonths = ["jan", "feb", "mar", "apr", "may", "jun", "aug", "sep", "oct", "nov", "dec"];


for(var x=0; x<allMonths.length; x++){

if(!$scope.monthlyData[x] || $scope.monthlyData[x].month === undefined){

        $scope.monthlyData.push(
        {
            "month":allMonths[x],
            "value":"0" 
        })
    }
}

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 to effectively trigger a function to load images in React

When my react app loads, I want the images to load immediately. This involves calling the function collectionChanged(e.target.value) on application start. Inside a .jsx file, there is a function named getHomePage() which contains 4 functions. Upon calling ...

What could be causing the video not to display in landscape mode on the iPad Pro?

I'm having an issue with a standard HTML5 <video> on my website. The videos are working fine on most devices, however there is a problem specifically with the iPad Pro in landscape orientation. It seems to work properly in portrait orientation ...

jquery plugin causing issues with bootstrap button functionality

Currently, I am utilizing the jQuery form plug-in to post my form in an Ajax way. The post function is functioning perfectly with the default button. However, it seems to encounter issues when I try to use a custom Bootstrap button as shown below. Could so ...

Using getElementsByTagName in E4X code involves querying for specific

Is it possible to retrieve an array of elements in E4X for an unknown tagname, similar to how the DOMs getElementsByTagName function works, within a function? My initial idea was: (function (doc, tag) { return doc..[tag]; }) Can this be achieved? ...

The (window).keyup() function fails to trigger after launching a video within an iframe

Here is a code snippet that I am using: $(window).keyup(function(event) { console.log('hello'); }); The above code works perfectly on the page. However, when I try to open a full view in a video iframe from the same page, the ke ...

Encountered an issue with reading the property 'drop' from an undefined source during a straightforward migration

I recently started using the migrate-mongo library and encountered an issue during a simple migration process to create a view. Despite success in migrating up, I faced an error when attempting to migrate down. ERROR: Could not migrate down 20220620114132 ...

What is the best way to initially hide a div using slide toggle and then reveal it upon clicking?

Is there a way to initially hide the div tag and then animate it in a slide toggle effect? I attempted using display:none on my '.accordion_box' followed by show() in slideToggle, but this results in adding the CSS property display: block. My goa ...

Create queries for relays in a dynamic manner

I'm using Relay Modern for my client GraphQL interface and I am curious to know if it is possible to dynamically generate query statements within Relay Modern. For example, can I change the original query structure from: const ComponentQuery = graphq ...

Problem with sidebar animation: Functioning properly when open, but closes abruptly without animation in React using Tailwind CSS

When interacting with my Menu react component by clicking on the 'hamburger' icon that I created manually, the sidebar menu opens smoothly with an animation. However, the issue arises when trying to close the sidebar as it vanishes instantly with ...

Determining the Size and Color of Squares in a Treemap Based on Content with D3.js

I encountered an issue with a treemap visualization. I came across an example that is similar to my situation, which can be viewed here: In the demo, you can see that the size of each square in the treemap is determined by the content size. However, all s ...

Sliding carousel from right to left

I'm currently working on setting up a slick carousel to continuously scroll, but I need it to move in the opposite direction. Despite trying to add the RTL option, I couldn't get it to work as intended. Check out my Fiddle here (currently scroll ...

Invoke a directive's function on a page by utilizing ng-click in AngularJS

Is there a way to call a function from a directive in an HTML page like index using ng-click? Below is the code for my directive: $scope.moreText = function() { $(".showMore").append(lastPart); }; html: <a ng ...

Refresh the PartialView only after clicking submit

I am struggling with updating only the contents of my partial view after clicking an input type="submit button. My goal is to refresh just the partial view and update it with the updated model from the controller code, without refreshing the entire page. S ...

Utilize the useState hook to update state when changes occur in the

I currently have a functional component that utilizes a useState hook. The values it holds are sourced from my redux store, and I aim to update the state with the new store state every time an action is dispatched. At the moment, I've manually set an ...

What is the best way to display two tables side by side in a Vue component?

I am working on a vue application with a photo collection feature. My goal is to display the photos in two tables per row, iterating through the entire collection. Here's an example of what I'm aiming for: <row> &l ...

Retrieving information from the backend with AngularJS

Is there a more efficient way to retrieve data from the backend when using AngularJS (or similar) in my web application? The current method I see involves rendering static HTML with JavaScript scripts, such as AngularJS, and then making AJAX requests to f ...

Executing NPM commands in a sequential manner

If I have the following npm scripts: "scripts": { "pre-build": "echo \"Welcome\" && exit 1", "build_logic": "start cmd.exe @cmd /k \"yo esri-appbuilder-js:widget && exit 1\"", "post_build": "start C:\ ...

Guide on accessing js file in an Angular application

I have a component where I need to create a function that can search for a specific string value in the provided JavaScript file. How can I achieve this? The file path is '../../../assets/beacons.js' (relative to my component) and it's named ...

The UnCSS exclusion feature seems to be malfunctioning

I am attempting to eliminate unnecessary CSS using uncss, but it seems to be removing all styles regardless of whether they are included in the ignore array. The two files I need to compare are the index file and the app.min.js file, which includes all te ...

The MDL layout spacer is pushing the content to the following line

Here's an interesting approach to Material Design Lite. In this example from the MDL site, notice how the 'mdl-layout-spacer' class positions elements to the right of the containing div, giving a clean layout: Check it out <!-- Event ca ...