Guidelines for calculating the total value within a specific time frame

For my current project, I am using LocalStorage to store an array of dates and costs. When the code localStorage.getItem("todos"); is executed in the console, the output looks like this:

"[{"due":"28/10/2017","task":"80"},{"due":"06/10/2017","task":"15"}]"

In this array, "due" represents the date and "task" represents the amount.

I have successfully calculated the total cost by utilizing the following method:

total: {
  type: String,
  value: () => {
    var values = localStorage.getItem("todos");
    if (values === undefined || values === null) {
      return "0";
    }
    var data = JSON.parse(values);
    var sum = 0;
    data.forEach(function(ele){ sum+=Number(ele.task)}); return sum;
  }
}

My next challenge is to calculate the total cost for the past six months. I am unsure about the approach that should be taken to accomplish this task. Any suggestions on how I can achieve this?

Answer №1

During your current iteration, ensure to implement a check to calculate the sum only for values within your specified date range. Incorporating a library such as moment can simplify this task significantly.

const data = [
  { due: '28/10/2017', task: 80 },
  { due: '06/10/2017', task: 15 },
  { due: '10/05/2000', task: 3000 }
];

const sixMonthsAgo = moment().subtract(6, 'months');

const total = data.reduce((acc, item) => {
  const dueDate = moment(item.due, 'DD/MM/YYYY');
  return acc + (dueDate.isAfter(sixMonthsAgo) ? item.task : 0);
}, 0);

console.log('total should equal 95: ', total);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.1/moment.min.js"></script>

Answer №2

Here is a unique solution to help resolve the issue at hand:

// By utilizing a forEach loop and performing a test, we can find the solution.
// Setting up an array of objects with dates and corresponding tasks
var todos=[{"due":"28/10/2017","task":"80"},{"due":"06/10/2017","task":"15"},{"due":"06/04/2017","task":"15"},{"due":"06/02/2017","task":"15"}];
var sum = 0;
var minDate = new Date();
var month = minDate.getMonth()+1-6; // calculating current month minus 6 months
var year = minDate.getFullYear(); // retrieving current year
if(month < 1){ // adjusting month based on condition
month+=6;
year-= 1;
}
minDate.setMonth(month); // updating min date by subtracting 6 months
minDate.setYear(year); // updating year if needed

todos.forEach(function(ele){
var arr = ele.due.split("/"); // extracting day, month, year from French date string
if(arr.length==3){
var dueDate = new Date(arr[2],arr[1],arr[0]); // creating task date object
if(dueDate>minDate){ // checking if task date is not too old
sum+=parseInt(ele.task); // adding task value to sum
}
}
});
console.log(sum);

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

An error occurred when attempting to search for 'length' using the 'in' operator in the context of the Datatables plugin and jQuery 1.11.3

I implemented the jQuery Datatables plugin in my tables for pagination, sorting, and searching functionalities. However, I am facing issues where the elements are not working properly, and the pagination occasionally fails to display. The Chrome console is ...

What steps can be taken to enable users to draw a path on a Google Map?

I'm working on a new project for a Facebook app that will allow users to map out their marathon route using Google Maps. I plan to utilize mySQL database records to store fixed points along the path (such as specific locations based on latitude and lo ...

Error message: SDL2 (emscripten) is encountering an unidentified data structure called "SDL_RendererFlip"

I have attempted to compile an SDL2 tutorial using emscripten found at this link: Text input tutorial However, I encountered the following error: error: unknown type name 'SDL_RendererFlip'; did you mean 'SDL_RendererFlags'? error: us ...

Ways to transform date into a different structure using JavaScript

Fetching a date from an API gives me this format: 2017-04-20T07:00:00Z How can I convert it to the following format? 20.04.2017 I am using React to render the date: <div>{props.data.day}</div> I attempted to use toISOString().slice(0, 1 ...

When using Jest, it is not possible to match 'undefined' using 'expect.any(Object)' or 'expect.anything()'

Looking to test the following module. import * as apiUtils from './apiUtils'; export function awardPoints(pointsAwarding) { return apiUtils.callApiService("POST", "points", pointsAwarding); } This is the test in question. it("should call ap ...

Using React JS to Sort an Array Based on a Specific String

Here I am again, this time dealing with reactjs. I have a json object containing two "rows", labeled as Description and ubication. My goal is to filter the array based on the Description field. How can I achieve this? The description is in text format, f ...

Is there a way to refresh CSS styles when the window width is adjusted?

Is there a way to refresh CSS styles when the window width changes? I attempted this method, but unfortunately it did not work as expected. A simple refresh (F5) helps to rectify the CSS tags. jQuery(function($){ var windowWidth = $(window).width(); ...

What is the method for concatenating two strings in JavaScript without any whitespace in between?

When working with two strings involving time, consider the following scenario: var gettime= $("#select-choice-2 :selected").text(); The above code returns a time value in 24-hour format, such as 17:45 However, if you require the time to display in the ...

Firebase Authentication error code "auth/invalid-email" occurs when the email address provided is not in a valid format, triggering the message "The email address is

Currently, I am working on integrating Firebase login and registration functionality into my Angular and Ionic 4 application. Registration of user accounts and password retrieval are functioning properly as I can see the accounts in my Firebase console. Ho ...

Select a different radio button to overwrite the currently checked one

I am facing a situation where I have two radio buttons. The default checked state is one of them, but I want to change that and make the other one checked by default instead. Here is the HTML code: <div class="gui-radio"> <input type="radio" v ...

Refreshing a Node.js server page upon receiving a JSON update

My web application serves as a monitoring interface for tracking changes in "objects" processed by the computer, specifically when they exceed a certain threshold. The Node Js server is running on the same machine and is responsible for displaying data in ...

The React Native app mysteriously crashes repeatedly without generating any error logs when using the same component multiple

Currently, I am developing in React Native app Version 0.70. Encountering a peculiar issue where the React Native app crashes without any error logs in the console. Below is the snippet of my code where most crashes seem to happen: import { ...

Passing a variable through jQuery onClick event to a URL via GET request and subsequently loading the content of

After successfully passing variables through AJAX calls via onClick to a PHP file and loading the results on the initial page, I now face the challenge of passing a variable analogously via onClick to a PHP file but this time I need to either open a new wi ...

Change to JSONArray using angularjs

Here is a json object: "values": [ {"name": "name1"}, {"name": "name2"}, {"name": "name3"} ] I want to convert it into this format: values: ["name1", "name2", "name3"]; Can this conversion be done in AngularJS or any other JavaScript functi ...

Obtain the final value within a URL's path segment

If we have an href similar to: http://localhost:8888/#!/path/somevalue/needthis Is there a way to extract the last value in the path string (i.e., "needthis")? I experimented with window.location.pathname, but it only returns "/". Another attempt was m ...

Searching for the search parameter in the Wordpress admin-ajax.php file. What could it

Just diving into the world of php and wordpress. Are there any search parameters I can include in admin-ajax.php? Here are the parameters in the ajax post; action: rblivep data[uuid]: uid_search_0 data[name]: grid_small_1 data[posts_per_page]: 8 data[pagin ...

Is there a solution to resolve the Firestore issue stating: "FieldPath.documentId is not a recognized function"?

In my function, I am retrieving data from two collections in Firestore: Media and Users. Inside the Users collection, there is a subcollection containing a list of all the user's movies. The Media collection includes details about each movie. My goal ...

In order to indicate the checkbox as checked, I must ensure that its value is set to

I have a requirement where I need to dynamically set the checkbox based on the value coming from the backend. If the value is true, the checkbox should be checked and if false, it should be unchecked. However, despite setting the value in the state rules, ...

Is there a way to verify the functionality of DigitalOcean features using doctl before transitioning to a live environment?

As a newcomer to using DigitalOcean Functions, I have set up some JavaScript namespaces using the doctl serverless command. My main query is regarding testing DigitalOcean functions locally before deploying them to production. Is there a way to do this wit ...

What is the best method for effectively eliminating duplicate objects with the same value from an array?

Let's say we have a collection of jqlite objects, and using the angular.equals function, we can determine if they are equal. How can we utilize this function to eliminate duplicate items from an array of jQlite objects? This is my attempted solution: ...