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

What could be causing the error message "Error: Cannot modify headers after they are sent" to appear?

I am attempting to insert data into an MS SQL server when a JSON Data API POST request is made. var express = require('express'); var app = express(); var sql = require('mssql'); // Connection string parameters. var sqlConfig = { u ...

Persistent hover state remains on buttons following a click event

In my current project, I am dealing with a form that has two distinct states: editing and visible. When the user clicks on an icon to edit the form, two buttons appear at the bottom - one for saving changes and one for canceling. Upon clicking either of th ...

Mongoose Does Not Allow for Duplicate Data Submissions

I'm currently working on a project to develop a basic blog application. Everything works smoothly when submitting content to the database for the first time, but if you try to submit again, Node crashes unexpectedly. I've been struggling to pinpo ...

jQuery: Implementing a function for all elements, including those dynamically loaded through Ajax later on

I have implemented a jQuery function to resize text areas, but I need it to work on all text areas. The function works well for existing text areas: $(document.ready(function(){$("text_area").resizer('250px')}); However, it fails to resize tex ...

What is the best way to access automatically generated JavaScript variables in TypeScript?

I am currently facing an issue with integrating a Google login API in my React project and I need some help. The problem arises when the user already has an active session, rendering the API unnecessary. The Javascript solution provided is as follows: co ...

Ways to direct to a specific div upon clicking an anchor tag following a page reload?

<a href="#goto">Link 1</a> <div id="goto">DIV</div> Whenever I click on the anchor tag, my webpage reloads and displays a new div with the ID of goto. This div was previously hidden but is now visible at the bottom of the page. I ...

Can D3 transform regions into drinking establishments?

I can create a graph using D3 areas, as shown in this example: Now, I want to add an animation to this graph. When the webpage loads, the initial figure will be displayed. Then, each area will morph into a bar chart. Additionally, users should be able to ...

Change the color when hovering over the select box

Using jQuery, my goal is to change the hover color in a select box from its default blue to red. I understand that the hover color of the select input may vary based on the operating system rather than the browser, but I am making progress towards achievin ...

Is coffeescript supported by Moovweb?

Lately, I've been researching the Moovweb platform and I'm curious about its compatibility with CoffeeScript. Could someone share a code example to demonstrate how Moovweb works with CoffeeScript? ...

Parse the contents of an XML file in C and output the tags

When faced with an XML file, my task is to identify, store, and print the unique tags it contains. For example, consider this XML File: <note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> & ...

Using JavaScript to interact with text elements in external SVG documents

When it comes to creating an SVG within HTML and assigning specific IDs to text elements for easy access, everything works smoothly. For example, I can easily retrieve the ID using: let callQSO = document.getElementById("QSOcall").value; and th ...

Create a binding between a keyboard shortcut and a button's click event in Angular

I am working on a div that has an ng-click event: <div class="modalWindowClose" ng-click="closeSettings(user, users);"><i class="fa fa-times"></i></div> I am trying to trigger a click on this element when the escape key is pressed ...

How can you prevent warnings in Perl regarding uninitialized elements within an array?

#!/usr/bin/perl use strict; use warnings; sub generateParagraph { open my $file, "<", "dict.txt" or die "$!"; my @words = <$file>; close $file; print "Number of lines:"; my $lines = <>; print "Max words per line:"; my $range = <>; ...

Backbone and Laravel - Choose a squad and automatically create users for the selected team

I've recently started exploring backbone.js and have gone through Jeffery Way's tutorial on using Laravel and Backbone. As of now, I have a list of teams being displayed along with their ids fetched from the database. I have also set up an event ...

Deciphering the hidden power of anonymous functions within Express.js

Recently, I started learning about express and am grappling with understanding callbacks in RESTful actions. In the following PUT request code snippet, I am puzzled by the specific line that is highlighted below. Why is response.pageInfo.book being assigne ...

What is the process for transforming a method into a computed property?

Good day, I created a calendar and now I am attempting to showcase events from a JSON file. I understand that in order to display a list with certain conditions, I need to utilize a computed property. However, I am facing difficulties passing parameters to ...

Increase the options available in the dropdown menu by adding more selected items, without removing any already selected

I came across this code on the internet http://jsfiddle.net/bvotcode/owhq5jat/ When I select a new item, the old item is replaced by the new item. How can I add more items without replacing them when I click "dropdown list"? Thank you <select id=&qu ...

Error 107 occurred while attempting to parse JSON data using the AJAX technique with the REST API

I've encountered an issue while attempting to utilize the Parse REST API for sending push notifications. Every time I make an AJAX call, I receive an invalid JSON error in the response and a status code of 400. Below is my request: $.ajax({ url: & ...

Swap out the hyperlink text for a dropdown menu when clicked and then revert back

Is there a way to dynamically switch between a label/text and a Kendo Combobox in a div using JavaScript when clicking on the text? The desired functionality includes: Clicking on the text displays the combobox, clicking away from it hides the combobox a ...

Specialized selection option with disabled function

Looking for assistance with a script to create a custom select box. I have UL and LI elements overlapping a select element, but I want to prevent the UL LI from opening when the select has a "disabled" attribute. Can anyone provide guidance on how to achie ...