My JS newbie question actually involves a few components (elaborated below), but I'd be happy with help just on the basics: How to calculate the difference between dates for selection of object values in in an array?
I realize there are a lot of examples on the internet for both creating iterative loops and examining the difference between dates. But most of these example calculating duration use one variable, and the examples on loops tend to include statements like // Do something
rather than providing examples for including functions. I haven't (yet) found a question that addresses this particular (simple) problem.
The closest that I have come so far is this, which seeks to calculate the difference between one of the object values and today:
durationArray = {
var myArray = report_data;
var arrayLength = report_data.length;
for (var i = 0; i < arrayLength; i++) {
var copy = new Date(report_data[i]["Start Date"]);
var duration_adjusted = (today - copy)/24/60/60/1000;
return duration_adjusted;
}
return myArray
}
With report_data
being supplied as:
report_data = [{
"Author Name": "Joe",
"Unit Name": "IT",
"Report Name": "Tech Paper 1",
"Start Date": "2/3/2014",
"End Date": "21-Mar-17"
},
{
"Author Name": "Carole",
"Unit Name": "IT",
"Report Name": "Tech Paper 2",
"Start Date": "4/8/2015",
"End Date": "5-May-16"
},
{
"Author Name": "Bob",
"Unit Name": "IT",
"Report Name": "Tech Paper 3",
"Start Date": "6/16/2015",
"End Date": "30-May-17"
},
{
"Author Name": "Sue",
"Unit Name": "IT",
"Report Name": "Tech Paper 4",
"Start Date": "7/16/2015",
"End Date": "pending"
}]
But this code is wrong, as it only returns one value (not values for all array objects). Also, I'd like to compare two object in the array ["Start Date"]
and ["End Date]
rather than only calculating the difference between today and the start date (but I haven't gotten this far in my attempts b/c I can't iterate correctly).
In case it helps to facilitate an answer, here's an Obeservable notebook with my errant code.
If you're feeling extra generous or would like more of a challenge (I realize this is an extremely basic question), then here's where the second part of the question comes in:
In the last item of my dummy data, instead of a date there's the value "pending" (indicating that the report isn't finished). In addition to calculating the difference between array objects ["Start Date"]
and ["End Date]
, I'd like to add an "else" statement that for "pending" values that calculates the difference between today
and ["Start Date"]
.
I hope this is clear and that I don't get slammed too hard for raising this very 'newbie' question. I am learning JS from home via tutorials, and have been struggling for a couple of days to combine them appropriately, so I turn to you for help.
Thanks in advance for your time and guidance!