Highcharts displaying additional information to each bubble points using array - javascript

I'm using a bubble chart. I represent "Ideas" in this chart. Each bubble is one specific idea with an X-value and a Y-value. What I need is the "Idea name" in the tooltip for each bubble as additional information.
I already know that you can do it as followed:
series: [{
data: [ { x : 1, y : 100, myIdea : 'Idea1' },
{ x : 2, y : 150, myIdea : 'Idea2' },
{ x : 5, y : 170, myIdea : 'Idea3' } ]
}]
But here comes the problem:
I used an array of this kind before:
dataArray [0][0] = 1; dataArray [0][1] = 100; dataArray [0][2] = 5;
dataArray [1][0] = 2; dataArray [1][1] = 150; dataArray [1][2] = 5;
coming from a loop.
My dataArray array then looked like that: [1,100,5], [2,150,5], ...
I gave that to the series like that:
series: [{
data: dataArray
}]
that worked perfectly!
How do I create an array in this expected format:
data: [ { x : 1, y : 100, myIdea : 'Idea1' },
{ x : 2, y : 150, myIdea : 'Idea2' },
{ x : 5, y : 170, myIdea : 'Idea3' } ]
Does this somehow work with associative arrays like that:
var myData= {
"x": "1",
"y": "100",
"myIdea": "idea1"
}
Btw, what is the best way to pass dynamic data for the bubblechart series?

You can loop over your current dataArray and build the new array like so:
var oldDataArray = [
[1, 100, 5],
[2, 150, 5]
];
var newDataArray = oldDataArray.map(function (row) {
return {
x: row[0],
y: row[1],
z: row[2]
};
});
console.log(newDataArray);

Related

javascript Array.push({y: yValue, label: myLabel}) setting random "x" key value

I am trying to create an canvasJS, JavaScript Bar Charts, with the following functions,
var dataPoints = [];
var headers;
var groups = [];
var cityWide = 0;
var chart = createChart();
function createChart(title = "Hospitalized Count") {
return new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
title:{
text:"Coronavirus Data in NYC Boroughs"
},
axisX:{
interval: 1
},
axisY2:{
interlacedColor: "rgba(1,77,101,.2)",
gridColor: "rgba(1,77,101,.1)",
title: "Total number of "+title
},
data: [{
type: "bar",
name: "companies",
axisYType: "secondary",
color: "#014D65",
dataPoints: dataPoints
}]
});
}
I am using this function below to set the dataPoints array:
function call: dataPoints = setDataPoints(4)
function setDataPoints(value){
let temp = [];
for(var i = 0; i<groups.length;i++){
if(groups[i][0] == "Citywide"){
continue;
}
yValue = groups[i][value];
myLabel = groups[i][0];
console.log("y: "+ yValue);
console.log("label: "+ myLabel);
temp.push(
{
y: yValue,
label: myLabel
});
}
console.log(temp);
return temp;
}
But when i console.log(dataPoints) I am getting this:
[
{"y": "136319","label": "Bronx","x": 0},
{"y": "202778","label": "Brooklyn","x": 1},
{"y": "97006","label": "Manhattan","x": 2},
{"y": "202737","label": "Queens","x": 3},
{"y": "54479","label": "StatenIsland","x": 4}
]
the expected result for dataPoints should be as follows:
[
{y:136319, label: "Bronx" },
{y:202778, label: "Brooklyn" },
{y:97006, label: "Manhattan" },
{y:202737, label: "Queens" },
{y:54479, label: "StatenIsland" }|
]
When I tried to set x
temp.push(
{
x: "123",
y: yValue,
label: myLabel
});
or delete temp[i]['x'] it doesn't work.
As you may of notice the x value are the indexes of the array, I have no idea why its being set and how do I even remove.
I have tried
dataPoints = temp;
console.log(dataPoints[0].hasOwnProperty('x'));
and returns false
Any help would appreciate it thanks in advance!
EDIT based of comment:
in for loop:
console.log(temp[i]['x']) returns undefined
If I add in to temp.push({ x: "123", ...})
console.log(temp[i]['x']) returns 123
console.log(temp[i]):
{y: "54479", label: "StatenIsland"}
label: "StatenIsland"
x: 4
y: "54479"
__proto__: Object
function.js:98
I'm not familiar with CanvasJS but my guess is that it's mutating the dataPoints array you give it to fill in the 'x' coordinate on the chart. console.log doesn't run synchronously, so by the time you see the output it's already been mutated.
If you console.log([...dataPoints]) or console.log([...temp]) I bet the x won't be there.
According to the API docs for dataPoints.x:
If not provided, it will be set automatically set according to its index position on dataPoints Array.
If you want to keep your "clean" copy of dataPoints you need to pass a copy of the array to the chart [...dataPoints].

Javascript Map function does not preserve the original object

I have a scenario wherein i have
var data = [
{
"x": 1,
"y": 0.27,
"classifier": 1
},
{
"x": 2,
"y": 0.88,
"classifier": 1
}
]
I want another object data2 with y=1-y, which i obtain with:
var data2 = data.map(function(el) {el.y = 1-el.y; return el});
data2[0]
Object {x: 1, y: 0.73, classifier: 1}
data2[1]
Object {x: 2, y: 0.12, classifier: 1}
which is the correct form that i want the data in. However the issue is i want to preserve the original data as well. Right now even data has mutated data.
data[0]
Object {x: 1, y: 0.73, classifier: 1}
data[1]
Object {x: 2, y: 0.12, classifier: 1}
Is map the right function to use here? Am i using it correctly?
While creating a new array, you let its values point to the original objects, which you mutate by assigning to their object properties.
Instead you could also create (shallow) copies of the objects with Object.assign:
var data2 = data.map(function(el) {
return Object.assign({}, el, { y: 1-el.y });
});
Or with arrow function:
var data2 = data.map( el => Object.assign({}, el, { y: 1-el.y }) );
var data = [
{
"x": 1,
"y": 0.27,
"classifier": 1
},
{
"x": 2,
"y": 0.88,
"classifier": 1
}
]
var data2 = data.map( el => Object.assign({}, el, { y: 1-el.y }) );
console.log (data);
You're modifying the original element object, which isn't a full deep copy of the original data.
Create a copy of el in the function and then calculate the new .y. For example:
var data2 = data.map(function(el) {
return {
x : el.x,
y : 1-el.y,
classifier : el.classifier
};
});

Javascript JSON not working after parsing

I need to get graph generated from Mysql database with help of PHP. I got nice application from (http://canvasjs.com). So, I created my own JSON format in variable element from PHP SESSION. It gies me no error when debugged, but no result.
Line number 34 - 37 gives me graph if I don't comment them. When comment them and replace with my own JSON which is variable element and does not give me graph. Gives me blank page.
I am new to JSON. Help me out with this.
Following are my codes.
var array = <?php echo json_encode($_SESSION["r_array"]); ?>;
var count = 0;
var element = '';
var title = 'Malware lab, TCRC, CTA';
for( var i in array) {
if ( count == 0 ) {
element += ‘{y: ‘+array[i]+’,’+’ indexLabel: “‘+i+'”}';
} else {
element += ‘, {y: ‘+array[i]+’,’+’ indexLabel: “‘+i+'”}';
}
count++;
}
var chart = new CanvasJS.Chart(“chartContainer”,
{
title: {
text: title
},
data: [
{ type: type,
dataPoints: [
/*
34 {y: 2, indexLabel: “Kaka'”},
35 {y: 3, indexLabel: “Blackberry”},
36 {y: 1, indexLabel: “Windows Phone”},
37 {y: 5, indexLabel: “Others”},*/
element,
]
}
]
});
chart.render();
Dumped array of $_SESSION["r_array"] as following
Array (
[Trojan] => 1
[Malware] => 3
[Backdoor] => 6
[Virus] => 2
[Bot] => 5
[Rootkit] => 7
[Worm] => 5
)
element must be an array, you are trying to create it as a string(with syntax errors)
var array = <? php echo json_encode($_SESSION["r_array"]); ?> ;
var count = 0;
var element = [];
var title = 'Malware lab, TCRC, CTA';
for (var i in array) {
element.push({
y: array[i],
indexLabel: i
})
count++;
}
var chart = new CanvasJS.Chart("chartContainer", {
title: {
text: title
},
data: [{
type: type,
dataPoints: element
}]
});
chart.render();
Demo: Fiddle
Yo need to pass array in correct Way
Use another variable datapoints = [];
and the push object into that array
var datapoints = [];
for( var i in array) {
datapoints.push({ y : array[i] , indexLabel : i});
}
and then use it as below
var chart = new CanvasJS.Chart(“chartContainer”,
{
title: {
text: title
},
data: [
{ type: type,
dataPoints: datapoints
}
]
});
chart.render();

Convert Js Array to JSON object with keys

I want to use the same object for jQplot and a library built on jQtable.
jQplot is fine with arrays but jQtable's library needs an named object (dictionary).
vals =
[
[1, 2],
[3,5.12],
[5,13.1],
[7,33.6],
[9,85.9],
[12,54],
[11,219.9]
];
This is my js array
I want it to be like
{
data: [{
X: 1,
Y: 2
},
{
X: 3,
Y: 5.12
},
{
X: 5,
Y: 13.1
}]
}
How to convert js array into named JSON array of objects? Are there any built in methods or I define my own method to read up that array and create a String for JSON?
var array = vals.map(function(val) {
return {
X : val[0],
Y : val[1]
};
});
var data = Object.keys(vals).map(function(key) {
return {X : vals[key][0], Y : vals[key][1]};
});

How can I merge two array of objects and concatenate values?

I have this two array of objects
var client = [{
"creazione": "1970-01-01",
"value": 2
}, {
"creazione": "2014-03-12",
"value": 4
}, {
"creazione": "2014-03-14",
"value": 1
}],
order = [{
"creazione": "1970-01-01",
"value": 1
}, {
"creazione": "2014-03-13",
"value": 5
}, {
"creazione": "2014-03-14",
"value": 1
}];
I need to merge these two arrays to get something like:
[{
x: '1970-01-01',
y: [2, 1]
}, {
x: '2014-03-12',
y: [4, 0]
}, {
x: '2014-03-14',
y: [1, 1]
}, {
x: '2014-03-13',
y: [0, 5]
}]
In few words I need to check if a.creazione == b.creazione then merge the key and concat the values in an array (first line of result), else if it is different, assign the value of the existing array in the right position of the y array (third line of result).
PS: I need to get this structure beacuse I'm using Angular-Charts library, and it ask for data in this uncomfortable way.
Any idea on how to achieve this?
Allow me to amuse you with the power of functional programming :)
client = _.object(_.map(client, _.values));
order = _.object(_.map(order , _.values));
var result = _
.chain(_.keys(client))
.union(_.keys(order))
.map(function (key) {
return [key, [client[key] || 0, order[key] || 0]];
})
.map(_.partial(_.zipObject, ['x', 'y']))
.value();
console.log(result);
# [ { x: '1970-01-01', y: [ 2, 1 ] },
# { x: '2014-03-12', y: [ 4, 0 ] },
# { x: '2014-03-14', y: [ 1, 1 ] },
# { x: '2014-03-13', y: [ 0, 5 ] } ]
Using plain JavaScript:
var result = [];
client.forEach( function( entry ) {
for( var i = 0; i < order.length; ++i ) {
if( entry.creazione === order[i].creazione ) {
result.push( { x: entry.creazione, y: [ entry.value, order[i].value ] } );
order.splice( i, 1 );
return;
}
}
result.push( { x: entry.creazione, y: [ entry.value, 0 ] } );
} );
order.forEach( function( entry ) {
result.push( { x: entry.creazione, y: [ 0, entry.value ] } );
} );
Fiddle: http://jsfiddle.net/rPk6e/
Note that for simplicity the order array is modified. If that is a problem for your use case simply make a copy using slice.

Categories

Resources