4đź‘Ť
How to fill in missing elements in an array describing a range
Presuming the starting array is already sorted, you might want to copy the first element in the source array into a new one and then iteratively push “default objects” into the destination array or copy from the source array when there is a matching object. Repeat until you reach the end of your range.
To check if there is a matching object, you might want to index first the source array by whatever parameter you want to iterate over (in your case: the “joined” field). This means that this parameter has to be unique.
function getIndex(srcArray, field) {
var i, l, index;
index = [];
for(i = 0, l = srcArray.length; i < l; i++) {
index[srcArray[i][field]] = srcArray[i];
}
return index;
}
This creates a hashmap of your array. Searching an element by it’s key (in your case the “joined” field) is very simple:
if(index['2013-06-05'] !== undefined) {
/* the element indexed by "2013-06-05" exists */
}
Now that you have an index, you can iterate over the range you expect to have. For this, get the first and the last dates in your source array:
//get boundaries
var first = new Date(src[0].joined);
var last = new Date(src[src.length-1].joined);
You also need to know how to construct your default objects:
function createDefault(datestr) {
return {users: 0, joined: datestr};
}
Now declare a destination array and iterate over the range:
var dest = [];
for(var d = first; d.getTime() <= last.getTime(); d.setDate(d.getDate()+1)) {
datestr = dateToYMD(d); //dateToYMD is a helper function I declared that formats a date
if(index[datestr]) {
//this date exists in your data, copy it
dest.push(index[datestr]);
} else {
//this date does not exist, create a default
dest.push(createDefault(datestr));
}
}
I made a jsfiddle that logs the destination array to console.
http://jsfiddle.net/uNasR/
0đź‘Ť
Try this:
function fixDate(data)
{
var myObjects=JSON.parse(data);
for(var i=0;i<myObjects.length;i++)
{
if(!myObjects[i].joined)
myObjects[i].joined="0";
}
return myObjects;
}
0đź‘Ť
function fix(json){
var updateUserToDate = function(object){
if (!object['joined']){ object.joined = 0 }
}
json.myjsonobject.forEach(updateUserToDate);
return json;
}
this is my version of it
if your data is still in string format you will need to call JSON.parse on it before you send it to this function, as Ewald Stieger points out
0đź‘Ť
I feel there is a little confusion.
Based on code you provided, I think you are using THIS ChartJS:
http://chartjs.devexpress.com
🙂
With that,I would try one more way to reach your goal: specify explicitely type of your arguments:
argumentAxis: {
grid: {
visible: true
},
//add this line to specify
argumentType: "datetime"
},
More info in ChartJS documentation