in my current project I need a Pie Chart in which calculated values should be displayed.
I have now five values as array, which I need to add, so that I have the desired value.
But now I am a bit confused, because no matter if I convert the arrays to sting, or use them directly in the addition, they are always lined up and not added.
What am I missing here?
In a subtraction directly after the calculation works, but here I still have a date value (number of days in the month) in the calculation.
Why does this calculation work?
My Problem
For example I get here "02400" as result and not "6".
var training = training_intervall + training_longrun + training_speedwork + training_stabilisation + training_competition;
My JS function:
function userDiaryMonthTrainingStats(user_id) {
$.ajax({
url: "../diary/includes/training/diary-training-monthly-training-stats.php?user_id=" + user_id,
type: "GET",
success: function(monthly_training_stats) {
var training_intervall = [];
var training_longrun = [];
var training_speedwork = [];
var training_stabilisation = [];
var training_competition = [];
var training_injury = [];
for(var i in monthly_training_stats) {
training_intervall.push(monthly_training_stats[i].training_intervall),
training_longrun.push(monthly_training_stats[i].training_longrun),
training_speedwork.push(monthly_training_stats[i].training_speedwork),
training_stabilisation.push(monthly_training_stats[i].training_stabilisation),
training_competition.push(monthly_training_stats[i].training_competition),
training_injury.push(monthly_training_stats[i].training_injury)
}
var date = new Date();
var month = date.getMonth() + 1;
var year = date.getFullYear();
daysInMonth = new Date(year, month, 0).getDate();
training_intervall = training_intervall.toString();
training_longrun = training_longrun.toString();
training_speedwork = training_speedwork.toString();
training_stabilisation = training_stabilisation.toString();
training_competition = training_competition.toString();
var training = training_intervall + training_longrun + training_speedwork + training_stabilisation + training_competition;
var training_free = daysInMonth - training_intervall - training_longrun - training_speedwork - training_stabilisation - training_competition - training_injury;
var userMonthlyTrainingStatsData = {
datasets: [{
data: [training, training_injury, training_free],
backgroundColor: ['#36a2eb', '#e33b3b', '#4bc07d']
}],
labels: [
'Training',
'Injury',
'Free'
]
};
........
}
})
}
use parseInt() to change from a string to int then you can add the strings as they are now numbers
var training = parseInt(training_intervall) + parseInt(training_longrun) + parseInt(training_speedwork + parseInt(training_stabilisation) + parseInt(training_competition);
if you want the result back to a string simply put after this
training=""+training
Two problems in your code:
training_intervall and the other 4 variables you want to add are arrays, you should iterate them.
The values are strings, using + with strings results in a new concatenated string. To convert easily a string number to a number (example "1" to 1), you can:
const myString = "1"
const myNumber = myString * 1 // myNumber = 1
Related
I assume it has something to do with timezone, but I cannot figure out how to add a day. I would like to only display the month. The issue is at the bottom of the code:
function compull() {
var linkssheet = SpreadsheetApp.openById("1hxkrSKhoUyveyK7dLr-xPpYxhZVvlKJt3S5L6rpMS7w").getSheetByName("Links");
var comsource = SpreadsheetApp.openById("1egqeIX6Lf2As2tsT0U8yhV41fg7as3dOLnwGryU9GVs");
var adjustmentssource = comsource.getSheetByName("Adjustments").getRange("A:I").getValues().filter(function(item){ return item[0] != ""; });
var compullsource = comsource.getSheetByName("Calculator").getRange("A:Q").getValues().filter(function(item){ return item[0] != ""; });
//var length = 4;
var length = 1 + getLastRowSpecial(linkssheet.getRange("E:E").getValues());
var comlength = 1 + getLastRowSpecial(compullsource);
var adjlength = 1 + getLastRowSpecial(adjustmentssource);
for (i=2; i<length; i++) {
var writelocation = SpreadsheetApp.openByUrl(linkssheet.getRange(i,5).getValue());
var compull = writelocation.getSheetByName("Commissions");
var id = linkssheet.getRange(i,1).getDisplayValue();
var id2 = linkssheet.getRange(i,2).getDisplayValue();
var rowlength = comlength;
var columnlength = compullsource[0].length;
dataarray = [];
dataarray.push(compullsource[0].slice());
for (j=1;j<compullsource.length;j++){
if(compullsource[j][1] == id){
dataarray.push(compullsource[j].slice());
}
}
for (k=0;k<dataarray.length;k++){
dataarray[k].splice(1,2);
}
compull.getRange(4,1,dataarray.length,dataarray[0].length).clearContent();
compull.getRange(4,1,dataarray.length,dataarray[0].length).setValues(dataarray);
var rowlength = adjlength;
var columnlength = adjustmentssource[0].length;
dataarray2 = [];
dataarray2.push(adjustmentssource[0].slice());
for (j=1;j<adjustmentssource.length;j++){
if(adjustmentssource[j][1] == id2){
dataarray2.push(adjustmentssource[j].slice());
}
}
for (k=0;k<dataarray2.length;k++){
dataarray2[k].splice(0,2);
}
compull.getRange(4,17,dataarray2.length,dataarray2[0].length).clearContent();
compull.getRange(4,17,dataarray2.length,dataarray2[0].length).setValues(dataarray2);
SpreadsheetApp.flush();
//change date in adjustments in Column Q
var date = compull.getRange("Q5:Q")
var values = date.getValues();
values[0][0] = Utilities.formatDate(date, "GMT-8:00", "MM");
You should know that the spreadsheet settings and the script project have their own timezone, so if you have problems with dates one of the first things that you should check is that each of them is using the correct timezone.
This part of the code is wrong
var date = compull.getRange("Q5:Q")
var values = date.getValues();
values[0][0] = Utilities.formatDate(date, "GMT-8:00", "MM");
The problem is that the first argument of formatDate should be a Date object but date had assigned a Range object.
Resources
Working with Dates and Times
how do I loop the newly created dynamic array by key and sub array.
var days = new Array();
$.each(json_object, function(r, row) {
var online_date = new Date(row.date_field * 1000);
var day_key = '' + online_date.getFullYear() + '' + (online_date.getMonth()+1) + '' + online_date.getDate() + '';
if(!days[day_key]) {
days[day_key] = [];
}
days[day_key][r] = row;
});
console.log('days.length');
console.log(Object.keys(days).length);
// 3 days woth of data..
// 20, 30 records each day...
for(var d = 0; d < Object.keys(days).length; d++) {
var day = days[d];
// day is undefined
console.log(day);
// I want KEY for 'day_key' and the data rows...
}
I'm using jQuery or basic JS.
If I filter or sort the array I loose my Keys, which I need as I want to graph out per day.
Thanks.
You should declare days as an object, not an array:
var days = {};
$.each(json_object, function(r, row) {
var online_date = new Date(row.date_field * 1000);
var day_key = '' + online_date.getFullYear() + '' + (online_date.getMonth()+1) + '' + online_date.getDate() + '';
if(!days[day_key]) {
days[day_key] = []; // Define an array for the rows to go into
}
days[day_key].push(row); // Add the row to the array
});
console.log('days.length');
console.log(Object.keys(days).length);
// 3 days worth of data..
// 20, 30 records each day...
Object.keys(days).forEach(day => {
console.log(day);
// I want KEY for 'day_key' and the data rows...
// The array of rows for the day are available
console.log(`Rows for ${day}: `,days[day])
})
I think this will do what you want
I'm currently a bit stuck trying to combine two arrays (one of dates, one of times).
I've written a PHP script to pass out JSON from an SQL table I have containing the data, but I'm struggling to turn the two arrays into a single datetime array in JavaScript.
The JSON is coming out as:
{
"dates": [
"2016-03-13",
"2016-03-13",
"2016-03-14",
"2016-03-14"
],
"times": [
"16:41:13",
"17:36:57",
"08:53:02",
"21:53:11"
]
}
So far I'm using this to collect the data, though I'm really not sure where to go from there (or if what I'm getting is even an array?):
$(document).ready(function() {
var API_URL = "php_script.php";
$.getJSON(API_URL, function(data) {
var dates = data.dates;
var times = data.times;
console.log(dates + " " + times);
});
});
The output of which is:
2016-03-13,2016-03-13,2016-03-14,2016-03-14,16:41:13,17:36:57,08:53:02,21:53:11
I'd prefer:
[2016-03-13 16:41:13,2016-03-13 17:36:57,2016-03-14 08:53:02,2016-03-14 21:53:11]
To be passed out as an array which I can then use with chart.js.
The dates and times will be used for the X axis and the time between them for the Y axis, so it would be useful to be able to complete some kind of datetime math on the data, if possible.
Here's a way to manually mix them together.... The gist is to manually splice the strings together and then use Date.parse() to make the date objects.
var dates = [
"2016-03-13",
"2016-03-13",
"2016-03-14",
"2016-03-14",
];
var times = [
"16:41:13",
"17:36:57",
"08:53:02",
"21:53:11",
];
var both = [];
for (var i = 0; i < dates.length; i++) {
both.push(new Date(Date.parse(dates[i] + " " + times[i])));
}
console.log("%j",both);
This sort of thing is easy if you use a library like lodash. In this case you would want _.zip
var dates = data.dates;
var times = data.times;
var zipped = _.zip(dates, times);
var text = _.reduce(zipped, function(aggregate, item) { return ',' + item[0] + ' ' + item[1]; });
console.log(text);
try splitting the dates and times with , and concat each of them by using loop
var data = {
"dates": [
"2016-03-13",
"2016-03-13",
"2016-03-14",
"2016-03-14"
],
"times": [
"16:41:13",
"17:36:57",
"08:53:02",
"21:53:11"
]
}
var datetimes = [];
for (var i = 0; i < data.dates.length; i++) {
datetimes.push(data.dates[i] + ' ' + data.times[i]);
}
document.write('<pre>' + JSON.stringify(datetimes, 0, 4) + '</pre>')
I just started working with JSON strings. i have an array of json strings that contains json strings like
{"ID":"3", "LinkFilename":"Test.txt", "Sender":"abc#hotmail.com", "Created":"2014-07-07T20:13:18.000Z"}
what i want to do is to take change the value of "Created" key (which is a date) and omit its time part so it must show only date part. i want to produce something like:
{"ID":"3", "LinkFilename":"Test.txt", "Sender":"abc#hotmail.com", "Created":"2014-07-07"}
The code to produce Json is as follows:
var ItemsEntries = [];
var listItemInfo = '';
var itemsCount = this.collListItem.get_count();
for (i = 0; i < itemsCount; i++) {
var item = this.collListItem.itemAt(i);
var ItemEntry = JSON.stringify(item.get_fieldValues());
ItemsEntries.push(ItemEntry);
listItemInfo += ItemsEntries[i].toString(); + '\n';
}
Please guide me through this.
If you have the Javascript object:
var item = {
"ID":"3",
"LinkFilename":"Test.txt",
"Sender":"abc#hotmail.com",
"Created":"2014-07-07T20:13:18.000Z"
}
and you want to change the Created field in the way you described, you can first create a new Date object out of the Created field value and just extracting the pieces you care about with the functions included in the Date API (http://www.w3schools.com/jsref/jsref_obj_date.asp).
This code should be able to change obj to the format you require:
var formatItem = function(item){
var date = new Date(item["Created"]);
var formattedDate = date.getFullYear()
+ '-'
+ date.getMonth() + 1 // zero-based index...
+ '-'
+ date.getDate();
item["Created"] = formattedDate;
};
One caveat is that the month won't be padded on the left by a 0 if it's a single digit, but that's easy enough to fix on a case-by-case basis.
I have a myDate variable with the value 18-Nov-2013.Each day its value is being changed.Tommorow this myDate variable will have the value 19-Nov-2013.I have a list of values that i have mapped into a single array named exclude which contains some dates that are to be excluded ,now it has values ["20-Nov-2013",21-Nov-2013", "23-Nov-2010"] .How could i filter my value from the list of values from the exclude array.I need the next highest value from the array.So here i need the value 22-Nov-2013 after tommorrows date.Could someone help me with this.
var excluded = ["30-Nov-2013","01-Dec-2013","02-Dec-2013"];
var myDate = "29-Nov-2013";
var month = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
var current = new Date(myDate);
while(true){
current = new Date((current.getDate()+1<10? "0"+(current.getDate()+1):(current.getDate()+1))+ "-" + month[current.getMonth()] + "-" + current.getFullYear());
var checkDate = (current.getDate()<10? "0"+(current.getDate()):(current.getDate()))+ "-" + month[current.getMonth()] + "-" + current.getFullYear();//this is necessary for when the +1 on day of month passes the month barrier
if(-1 == excluded.indexOf(checkDate))
break;
}
alert(checkDate);
I don't know if this is the best approach, or if is the best algorithm, but you may try this:
var myDate = ["17-Nov-2013", "18-Nov-2013"];
var excluded = ["20-Nov-2013", "21-Nov-2013", "23-Nov-2013"];
var months = {"Nov": 10}; // Add others months "Jan": 1, "Fev": 2 etc...
function findExcluded(date)
{
for (var i = 0; i < excluded.length; i++)
{
if (excluded[i] === date)
{
return true;
}
}
return false;
}
function nextDate()
{
var last = myDate[(myDate.length - 1)];
var s = last.split("-");
var d = new Date(s[2], months[s[1]], s[0]);
var next = new Date(d);
var chkDate = "";
do
{
next.setDate(next.getDate() + 1);
chkDate = next.getDate() + "-" + findMonth(next.getMonth()) + "-" + next.getFullYear();
} while(findExcluded(chkDate));
return chkDate;
}
function findMonth(m)
{
var i = 10; // When you fill all months on 'months' array, this variable should start at '0' in order to loop to works.
for (var month in months)
{
if (i == m)
{
return month;
}
i++;
}
}
var nd = nextDate();
alert(nd);
See it woring here.
No code ? Well here will be my method:
1.Get next date for mydate. Say that is var nextDate.
2.Check whether that date exist in the array.
3.If exists add one more day to nextDate. Again check in the array.
4.Do it until you get a date which is not present in your exclude array
For checking whether it exists in the array you can use arrValues.indexOf(nextDateInProperFormat) > -1