jqPlot adding 0 value - javascript

I'm using the jqPlot library to build charts. I'm using some JS to fetch a JSON file, build a string using values from the JSON file, convert it to a nested array (the only format that jqPlot likes) and then passing to jqplot. jqPlot is reading the arry just fine and is plotting the correct values, but its adding a 0 value at the end.
Here's the string code:
$(function () {
$.getJSON("test.json", chartData);
function chartData(data) {
$.each(data.values, function(index,val){
chartValues += val + ",";
});
};
here's the code that converts it into a nested array:
var temp = new Array();
temp = chartValues.split(',');
var temp2 = new Array(temp);
alert(temp2);
So when temp2 is passed to jqplot it adds a zero, but when I pass it an identical nested array called test that is declared manually, it doesn't add the zero. Here they are for comparison:
var test = [[12,32,21,23,34,43,52,86,25,]];
and here's temp2
[[12,32,21,23,34,43,52,86,25,]]
Any ideas? I'd also appreciate any help with my logic in this, as I feel like I could be creating the nested array more elegantly.

I'm not sure 100% at this point but I think in .....86,25,]] is not right. That might be the reason to add a zero value. Try eliminating this. Another thing is that you can access the data arrays in json files directly using basic access methods. Try at json org.

Removing the last character in the string (before converting to an array) was the solution in this case.
newStr = chartValues.substring(0, chartValues.length-1);

Related

find value in complex object javascript

Basically I have a complex object that retrieves the GPT API (google publisher tag) with this function:
googletag.pubads().getSlots();
The object value is something like this:
I need to know if there is a way to compare the value of each property with an X value without getting a problem of recursivity (because the object is huge and i need to to that validation several times)
Also, I tried to convert that object into a JSON with JSON.stringify(), and then tried to get the value with a regex, faster, but with this option, I have the problem with Cyclic Object Value.
Any suggestions ?
it's more simple. try it to convert it into an array and later use a filter for comparative with your value.
var objGoogle = {};
var arrayObjectGoogle = [objGoogle];
var filter = arrayObjectGoogle.filter(function(obj){
obj.yourAttr == yourValue; });
this will give you a second array with the values found it. later, index the array for pick up the value do you need.

fastest way to filter array of strings in JavaScript

I am working with some xml files stored on S3. I use the xml2js module in Node to parse the xmls and then I extract the strings that have .jpg in them. I was using the filter method and then tried using my own for loop but that didn't shave any time off. Is there any faster way to write this section of the code or is this the fastest way to get it done. Any help appreciated.
using filter method:
//this took 52393ms
var file = JSON.stringify(data);
var arrayOfStrings = file.split('"');
var images = arrayOfStrings.filter(function(str) {
return str.indexOf('.jpg') !== -1;
});
resolve(images);
using for loop:
//this took 52681ms
var file = JSON.stringify(data);
var arrayOfStrings = file.split('"');
var images =[];
for(let i = 0; i < arrayOfStrings.length; i++) {
if(arrayOfStrings[i].indexOf('.jpg') !== -1) {
images.push(arrayOfStrings[i]);
}
}
resolve(images);
data looks like the following after I use file.split('"');
[ '{','rstuv',':{','options',':[{','![alt](CKrgUgiYMflaWnsGZ009.jpg)']];
var file = JSON.stringify(data);
var arrayOfStrings = file.split('"');
Don't do that. If you want to search through data, keep it structured. Stringifying and then searching that string will not only get you a bunch of mistakes (when strings did contain a quote), lots of array elements that are not even proper strings, and is hardly any improvement over just reading in the original XML file as text and directly searching that.
Instead, just iterate (or recurse if necessary) through the data object (see Access / process (nested) objects, arrays or JSON for details), and filter for the strings (and property names?) in those locations where you expect them. This will be a lot faster.

Why doesn't flot work with a array of (x,y) values? Javascript object versus arrays?

I'm creating a flot graph using some php-script. The php generates the data and uses json_encodeto pass this data to some javascript-flot code where I parse using jQuery.parseJson.
I was using the data-array filled with (x,y) values. Plotting this doesn't seem to work. If I encapsulate the array within an object flot is plotting it without problems. Why doesn't the first method work? I've added a jsFiddle below.
var data = '[["201518","1"],["201519","3"],["201520","6"]]',
data2 = '{"data":[["201518","1"],["201519","3"],["201520","6"]]}';
var set = jQuery.parseJSON(data),
set2 = jQuery.parseJSON(data2);
var placeholder = $('#placeholder');
$.plot(placeholder, [set2.data]);
//$.plot(placeholder, set); <= not working? Why?
jsfiddle
You need to pass an array:
$.plot(placeholder, [set])
// instead of `$.plot(placeholder, set)`
Two problems. First you need numbers and not strings when passing as an array (see here where it says
Note that to simplify the internal logic in Flot both the x and y
values must be numbers (even if specifying time series, see below for
how to do this). This is a common problem because you might retrieve
data from the database and serialize them directly to JSON without
noticing the wrong type. If you're getting mysterious errors, double
check that you're inputting numbers and not strings.
Second (as pointed out in another answer), you need the [array] around set. The following works:
$(document).ready(function () {
var data = '[[201518,1], [201519,3], [201520,6]]',
data2 = '{"data":[["201518","1"],["201519","3"],["201520","6"]]}';
var set = jQuery.parseJSON(data),
set2 = jQuery.parseJSON(data2);
var placeholder = $('#placeholder');
//$.plot(placeholder, [set2.data]);
$.plot(placeholder, [set]);
});

Retrieving values in crossfilter.dimension

Hi I'm a newbie in JS and Crossfilter. I'm using crossfilter with my data (.csv file) and retrieved distinct values in a column using
var scoreDim = ppr.dimension(function (d) {
return d.score;
});
Also I could get the counts for each value using
var scoreDimGroup = scoreDim.group().reduceCount();
I could use dc.js to plot the chart and the result looks correct. But how do I retrieve the values in scoreDim and scoreDimGroup so that I can use it for further processing in my code. When I look at the object using a debugger, I could see a bunch of functions but could not see the actual values contained in the objects.
scoreDim.top(Infinity)
will retrieve the records.
scoreDimGroup.top(Infinity)
will retrieve the groups (key-value pairs of the dimension value and the count).
Generally, this kind of thing is covered well in the Crossfilter API documentation.
You can use the top method of the group object:
var groupings = teamMemberGroup.top(Infinity);
This returns an array of groups, which will have the structure that you built in the reduce method. For example, to output the key and value you can do this:
groupings.forEach(function (x) {
console.log(x.key + x.value.projectCount);
});
You can access the dimension values in the same way:
var dimData = teamMemberDimension.top(Infinity);
dimData.forEach(function (x) {
console.log(JSON.stringify(x));
});
Here is a simple example of this: http://jsfiddle.net/djmartin_umich/T5v4N/
Rusty has a nice tutorial on how this works at http://blog.rusty.io/2012/09/17/crossfilter-tutorial/
If you are looking to view these values in the console then you can use this print_filter function that was mentioned in the tutorial!
(http://www.codeproject.com/Articles/693841/Making-Dashboards-with-Dc-js-Part-1-Using-Crossfil)
Basically you would include this bit of code in your javascript rendering of the crossfilter charts before you define your data source or your ndx variable:
function print_filter(filter) {
var f = eval(filter);
if (typeof(f.length) != "undefined") {}else{}
if (typeof(f.top) != "undefined") {f=f.top(Infinity);}else{}
if (typeof(f.dimension) != "undefined") {f=f.dimension(function(d) { return "";}).top(Infinity);}else{}
console.log(filter+"("+f.length+") = "+JSON.stringify(f).replace("[","[\n\t").replace(/}\,/g,"},\n\t").replace("]","\n]"));
};
Then you can simply run print_filter(scoreDim) in your console! It's that simple! You can use this to see all of the objects you create using crossfilter including groups, etc.
Hope this helps!

How can I store values from one array to another array using 'for' loop

I am trying to create number of arrays like _temp0[],_temp1[],_temp2[] so on and I want to store values of data[] in it.
so value of data[0] goes in array_temp0[] after splitting,
data[1] goes in _temp1[] and so on
to elaborate more-
If value of data[0] is string a,b,c
then array _temp0[] should be
_temp0[0]=a
_temp0[1]=b
_temp0[2]=c
I wrote this function
for(var k=0;k<data.length-1;k++)
{
window['_temp' + k] = new Array();
alert("actual data -- >"+data[k]);
'_temp'+k= data[k].split(',');
alert("data after split -- >"_temp[k]);
}
but it is not working, how do I solve it?
You can do the same using javascript objects. Here is an example of how to do it.
Create an object of name '_temp':
var _temp = {};
When you iterate through 'data' variable then, you can dynamically add attributes to it,say _temp['data0'], _temp['data1'] etc, and every attribute will be an array. For that, you need to write something like:
for(var k=0;k<data.length-1;k++)
{
_temp['data'+k] = data[k].split(',');
}
This will not create the variables identical to what you want. However, this is similar to what you want.
used
window['_temp'+k]= data[k].split(',');
instead of
'_temp'+k= data[k].split(',');
and it worked, thanks to go-oleg

Categories

Resources