Calculating the annual total in angular 4 - a step-by-step guide

I have successfully calculated the sum of costs between each other, but now I am facing a challenge in summing up the total budget for the entire year. I have attempted to achieve this, but unfortunately, I am encountering an issue as it is showing me 'undefined.'

The 'Costs' interface consists of a variable created with a type date, a variable 'costs' with a type number, and the ID of the actual costs being sent to an array called 'actualcostIds.' How can I calculate the total sum from January 1st to December 31st? Below you will find my code for calculating the sum for each cost and the total summed costs.

  export interface TotalCosten {
  planned: number;
  actual: number;
}


export function emptyCosts(): Costs {
  return {
    id: '',
    created: new Date(),
    type: 0,
    costs: 0,
    reference: '',
    comment: ''
  };
}



export function getTotalYearCosts(valueItem: ValueItem, allCosts: Map<string, Costs>): TotalCosten {
const totalYearCosts = { planned: 0, actual: 0 };

const Q1 = new Date(2018, 11, 31);
const Q2 = new Date(2018, 0, 1);
  totalYearCosts.actual = valueItem.actualCostIds
.map(costId => allCosts.get(costId, emptyCosts()).costs)
.filter() //Here to make a filter for costs that are in the date range
.reduce((reduction, costs) => reduction + costs, 0);
  return totalYearCosts;
}
export interface ValueItem {
 plannedCostIds: string[];
  actualCostIds: string[];
}

Answer №1

It seems like if I comprehend your English accurately, you have the option to enhance your reduce function to include a date check.

Is there a way to calculate the total sum based on the specific date?

.reduce((reduction, costs) => {
    if (verifyDate) {
        return reduction + costs;
    } else {
        return 0;
    }
}, 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

Parallel mapping with simultaneous multiple inserts

I am working on inserting a list of topics with unique slugs into a MongoDB database. Here are two example topics: { title: "my title" }, { title: "my title" } After generating the slugs, I need to insert the topics: // Insert each topic async.map( ...

Is there a way to showcase all components on a single page in Angular 2 without needing to bootstrap them in appModule?

Is there a way to showcase all my Angular 2 components on one page without having to bootstrap them individually in AppModule.ts? I'm looking for a solution using router-outlet or parent-child relationships. Any guidance on how to achieve this after s ...

Struggling to understand the concept of utilizing Promises for data retrieval

I'm currently facing an issue with my async function that awaits a GraphQL call. Even though the call returns a Promise containing the desired data, I'm struggling to access it effectively. Below is the snippet of code in question: export async ...

Using JavaScript to Establish Default Homepage in FireFox and Internet Explorer

How can I set a web address as the default homepage for a client? Specifically looking for solutions for (pageload) on IE8 and Firefox 3 (or newer versions). Thank you in advance for your help. Best regards ...

Tips for integrating custom code into your Angular cli service worker

Although I have successfully generated and configured the service worker using a config file generated by Angular CLI, I am struggling to find documentation on how to add custom code to the ngsw-worker.js file. I want to include functions such as push no ...

Having trouble with the "Like Button" feature in Tango with Django?

I attempted to follow a tutorial for adding a like button, but unfortunately the like count is not increasing after clicking it. The tutorial can be found at this link. Below is the code I have implemented: views.py def like_post(request): post ...

The ComponentFactory<any> 'DynamicComponent' cannot be associated with undefined

After researching how to render an MVC View into Angular 2, I came across this helpful directive export function createComponentFactory(compiler: Compiler, metadata: Component): Promise<ComponentFactory<any>> { const cmpClass = class Dynamic ...

HttpClient experiences a timeout in processing the request

Currently, I am utilizing TypeScript in conjunction with ASP.NET Core Web API. Situation: I am facing a challenge with a backend data response service that is taking more than two minutes to load the data. It appears that the default timeout for the Http ...

What is the process for finding GitHub users with a specific string in their name by utilizing the GitHub API

I'm looking to retrieve a list of users whose usernames contain the specific string I provide in my query. The only method I currently know to access user information is through another endpoint provided by the GitHub API, which unfortunately limits t ...

Utilizing NodeJS and Express to enhance the client side for showcasing an uploaded file

My knowledge of nodeJS, AJAX requests, and routing is still in its infancy. After following a tutorial on nodejs and express examples, I managed to get everything working on the server-side. However, I'm facing difficulty displaying the uploaded file ...

The async waterfall is encountering a Typeerror due to the nextcallback function not being defined properly

async.waterfall([1,2,3,4].map(function (arrayItem) { return function (lastItemResult, nextCallback) { // performing the same operation for each item in the array var itemResult = (arrayItem+lastItemResult); // pa ...

What is the method to trigger the jQuery 'mouseenter' event on an element using Selenium?

Struggling to automate a scenario using selenium where I need to click on a menu element. I've tried various methods, except jQuery. WebDriver normal click and JavaScript click() haven't worked. Can someone assist me with implementing jQuery in s ...

How do I set a new value for a variable from within a function?

After retrieving initial numbers from a JSON file, I want to update them using an ajax call. How do I go about replacing the values of homePoints and awayPoints with the new ones fetched through ajax? I have reviewed the provided answers but none seem to ...

Tips for identifying and handling a 400 bad request error in an HTTP response within an Angular 2 application

I attempted to handle the error 400 bad request in this manner: catch((error: any) => { if (error.status === 500) { return Observable.throw(new Error(error.status)); } else if (error.status === 400) { console.log( 'err ...

Tips for displaying an error message when there is no match found in ng repeat due to filtering

I'm facing an issue with displaying an error message when no match is found after searching in a text box. I've used ng-show to display the message, but it's not working as expected. Can someone assist me with this problem? I am relatively n ...

Why is it that a click event outside of an HTML element cannot be detected in this Vue 3 application?

I've been diving into building a Single Page Application using Vue 3, TypeScript, and The Movie Database (TMDB). Currently, I'm focused on developing a search form within my project. Within the file src\components\TopBar.vue, here&apo ...

How does SWR affect React state changes and component re-rendering?

I am currently utilizing SWR for data fetching as outlined in the documentation: function App () { const [pageIndex, setPageIndex] = useState(0); // The API URL incorporates the page index, which is a React state. const { data } = useSWR(`/api/data? ...

Is there a way to imitate the typeof operation on an object in TypeScript?

Today's challenge is a strange one - I've encountered a bug where the code behaves differently if typeof(transaction) returns object instead of the object name. To work around this issue, I introduced a new parameter called transactionType to my ...

Clearing the JSON data from the file object

I am encountering an issue that requires me to pass some information along with a file to a controller using an Ajax call. The model structure is as follows: public class PersonModel { [Display(Name ="Full Name")] public string Name { ...

Is there a way to make all cards in material ui the same height?

My challenge lies in rendering cards in a grid list using material-ui. Each card comprises an image file at the top and some content in the rest of the space. However, variations in text content cause differences in card height. Despite several attempts, I ...