How to hide undefined? - anychart

How to hide empty/undefined values for
chart type: anychart.stock();
Screen was made with next data:
var dataTable2 = anychart.data.table();
dataTable2.addData([
["2016-12-24", 518.40],
["2016-12-25", 519.34],
]);
var dataTable3 = anychart.data.table();
dataTable3.addData([
["2016-12-24", undefined],
["2016-12-25", 524.34],
]);
var mapping3 = dataTable3.mapAs(
{ value: 1}
);
var mapping2 = dataTable2.mapAs(
{ value: 1}
);
With one undefined is not a big problem but what if I have 20? It would be take time to find defined value
It is useless information for my opinion and decreasing speed for understanding chart
The same result after manually delete field
test_issue(){
function filterUndefinedPoints(data) {
return data.filter((row) => row[1] !== undefined);
}
var dataTable2 = anychart.data.table();
dataTable2.addData([ // these are not filtered
["2016-12-24", 518.4],
["2016-12-25", 519.34],
]);
var dataTable3 = anychart.data.table();
dataTable3.addData(filterUndefinedPoints([ // these are filtered
// ["2016-12-24", undefined], // this will be removed
["2016-12-25", 524.34],
]));
var mapping3 = dataTable3.mapAs({ value: 1 });
var mapping2 = dataTable2.mapAs({ value: 1 });
var chart = anychart.stock();
var plot = chart.plot(0);
var a = plot.marker(mapping2);
var b = plot.marker(mapping3);
chart.container("container");
chart.draw();
}
Its happening when I have several markers in one plot. The markers dependent of dataset of each other but I dont' want it

You can create a helper function that filters out any entries that have undefined values:
function filterUndefinedPoints(data) {
return data.filter((row) => row[1] !== undefined);
}
Then use that when passing in your data points that can have undefined values:
var dataTable2 = anychart.data.table();
dataTable2.addData([ // these are not filtered
["2016-12-24", 518.4],
["2016-12-25", 519.34],
]);
var dataTable3 = anychart.data.table();
dataTable3.addData(filterUndefinedPoints([ // these are filtered
["2016-12-24", undefined], // this will be removed
["2016-12-25", 524.34],
]));
var mapping3 = dataTable3.mapAs({ value: 1 });
var mapping2 = dataTable2.mapAs({ value: 1 });

Related

Isotope: Combined multiple checkbox and searchbox filtering

I'm trying to combine the Isotope multiple checkbox filtering with a searchbox.
I used the example with the checkbox filters from here and tried to implement the searchbox but with no luck.
Just the checkbox filtering works well. I think i'm close to the solution but my javascript skills are at a very beginner level.
I commented out the section of what i've tried to implement.
Thank you for some hints
// quick search regex
var qsRegex;
var $grid;
var filters = {};
var $grid = $('.grid');
//set initial options
$grid.isotope({
layoutMode: 'fitRows'
});
$(function() {
$grid = $('#grid');
$grid.isotope();
// do stuff when checkbox change
$('#options').on('change', function(jQEvent) {
var $checkbox = $(jQEvent.target);
manageCheckbox($checkbox);
var comboFilter = getComboFilter(filters);
/*var searchResult = qsRegex ? $(this).text().match(qsRegex) : true;
var filterResult = function() {
return comboFilter && searchResult;
}*/
$grid.isotope({
filter: comboFilter //or filterResult
});
});
});
function getComboFilter(filters) {
var i = 0;
var comboFilters = [];
var message = [];
for (var prop in filters) {
message.push(filters[prop].join(' '));
var filterGroup = filters[prop];
// skip to next filter group if it doesn't have any values
if (!filterGroup.length) {
continue;
}
if (i === 0) {
// copy to new array
comboFilters = filterGroup.slice(0);
} else {
var filterSelectors = [];
// copy to fresh array
var groupCombo = comboFilters.slice(0); // [ A, B ]
// merge filter Groups
for (var k = 0, len3 = filterGroup.length; k < len3; k++) {
for (var j = 0, len2 = groupCombo.length; j < len2; j++) {
filterSelectors.push(groupCombo[j] + filterGroup[k]); // [ 1, 2 ]
}
}
// apply filter selectors to combo filters for next group
comboFilters = filterSelectors;
}
i++;
}
var comboFilter = comboFilters.join(', ');
return comboFilter;
}
// use value of search field to filter
var $quicksearch = $('.quicksearch').keyup(debounce(function() {
qsRegex = new RegExp($quicksearch.val(), 'gi');
$grid.isotope();
}, ));
// debounce so filtering doesn't happen every millisecond
function debounce(fn, threshold) {
var timeout;
threshold = threshold || 100;
return function debounced() {
clearTimeout(timeout);
var args = arguments;
var _this = this;
function delayed() {
fn.apply(_this, args);
}
timeout = setTimeout(delayed, threshold);
}
}
function manageCheckbox($checkbox) {
var checkbox = $checkbox[0];
var group = $checkbox.parents('.option-set').attr('data-group');
// create array for filter group, if not there yet
var filterGroup = filters[group];
if (!filterGroup) {
filterGroup = filters[group] = [];
}
var isAll = $checkbox.hasClass('all');
// reset filter group if the all box was checked
if (isAll) {
delete filters[group];
if (!checkbox.checked) {
checkbox.checked = 'checked';
}
}
// index of
var index = $.inArray(checkbox.value, filterGroup);
if (checkbox.checked) {
var selector = isAll ? 'input' : 'input.all';
$checkbox.siblings(selector).prop('checked', false);
if (!isAll && index === -1) {
// add filter to group
filters[group].push(checkbox.value);
}
} else if (!isAll) {
// remove filter from group
filters[group].splice(index, 1);
// if unchecked the last box, check the all
if (!$checkbox.siblings('[checked]').length) {
$checkbox.parents('.option-set').find(selector).prop('checked', false);
}
}
I found the solution by myself, but i had to add a second function for returning the searchresult. Otherwise the search function is triggered only after using a checkbox or leaving the search box input field.
How could i avoid this redundand code?
JS:
// use value of search field to filter
var $quicksearch = $('.quicksearch').keyup(debounce(function() {
qsRegex = new RegExp($quicksearch.val(), 'gi');
$grid.isotope();
}, 200));
$(function() {
$grid = $('#grid');
$grid.isotope({
filter: function() {
var searchResult = qsRegex ? $(this).text().match(qsRegex) : true;
return searchResult;
}
});
// do stuff when checkbox change
$('#options').on('change', function(jQEvent) {
var $checkbox = $(jQEvent.target);
manageCheckbox($checkbox);
var comboFilter = getComboFilter(filters);
$grid.isotope({
filter: function() {
var buttonResult = comboFilter ? $(this).is(comboFilter) : true;
var searchResult = qsRegex ? $(this).text().match(qsRegex) : true;
return buttonResult && searchResult;
}
});
});
});

combine two array as key value pair

I have two array as follows
var field_array=["booktitle","bookid","bookauthor"];
var data_array=["testtitle","testid","testauthor"];
I want to combine these two array and covert it to the following format
var data={
"booktitle":"testtitle",
"bookid":"testid",
"bookauthor":"testauthor"
}
I want to insert this data to database using nodejs
var lastquery= connection.query('INSERT INTO book_tbl SET ?',data, function (error, results, fields) {
if (error) {
res.redirect('/list');
}else{
res.redirect('/list');
}
});
Please help me to solve this.
var field_array = ["booktitle", "bookid", "bookauthor"];
var data_array = ["testtitle", "testid", "testauthor"];
var finalObj = {};
field_array.forEach(function (eachItem, i) {
finalObj[eachItem] = data_array[i];
});
console.log(finalObj); //finalObj contains ur data
You also can use reduce() in a similar way:
var field_array=["booktitle","bookid","bookauthor"];
var data_array=["testtitle","testid","testauthor"];
var result = field_array.reduce((acc, item, i) => {
acc[item] = data_array[i];
return acc;
}, {});
console.log(result);
Here I explaned my code line by line..Hope it will help
var field_array = ["booktitle", "bookid", "bookauthor"];
var data_array = ["testtitle", "testid", "testauthor"];
//Convert above two array into JSON Obj
var jsondata = {};
field_array.forEach(function (eachItem, i) {
jsondata[eachItem] = data_array[i];
});
//End
//Store Jsondata into an array according to Database column structure
var values = [];
for (var i = 0; i < jsondata.length; i++)
values.push([jsondata[i].booktitle, jsondata[i].bookid, jsondata[i].bookauthor]);
//END
//Bulk insert using nested array [ [a,b],[c,d] ] will be flattened to (a,b),(c,d)
connection.query('INSERT INTO book_tbl (booktitle, bookid, bookauthor) VALUES ?', [values], function(err, result) {
if (err) {
res.send('Error');
}
else {
res.send('Success');
}
//END

make value of one( key value pair )to be key of another in angular js

i am having a json response from which i wanted to create new json object
response = [
{Detail:"Reuters ID",keyName:"Reuters_ID"},
{Detail:"Parity One",keyName:"parity_one"},
{Detail:"Parity level",keyName:"parity_level"}
];
i wanted to achieve this after manipulating keys and value pair
lang_Arr =[
{Reuters_ID:"Reuters ID"},
{parity_one:"Parity One"},
{parity_level:"Parity level"}
];
i have tried doing it in two ways
1) in this getting error as unexpected tokken (.)
var Lang_arr =[];
angular.forEach(response, function(value, key) {
Lang_arr.push({value.keyName:value.Detail});
});
2) here getting unxepected token [
var Lang_arr =[];
angular.forEach(response, function(value, key) {
Lang_arr.push({value['keyName']:value['Detail']});
});
i have tried assigning the values seperatly too but it doesn't work there also
var Lang_arr=[];
var k ='';
var v ='';
var i = 1;
angular.forEach(response, function(value, key) {
k ='';
v ='';
i = 1;
angular.forEach(value,function(val,key){
if(i == 1 )
k = val;
if(i == 2)
v = val;
if(!empty(k) && !empty(v))
Lang_arr.push({k:v})
i++;
});
});
You can use javascript map function to map the objects to array
var response = [
{Detail:"Reuters ID",keyName:"Reuters_ID"},
{Detail:"Parity One",keyName:"parity_one"},
{Detail:"Parity level",keyName:"parity_level"}
];
var lang_Arr =[];
lang_Arr = response.map(function(o){
var obj = {};
obj[o.Detail] = o.keyName;
return obj;
})
console.log(lang_Arr)
With Angular forEach also you can achieve this functionality
var response = [
{Detail:"Reuters ID",keyName:"Reuters_ID"},
{Detail:"Parity One",keyName:"parity_one"},
{Detail:"Parity level",keyName:"parity_level"}
];
var modifiedArray = [];
angular.forEach(response, function(val, key) {
var res = {};
res[val.keyName] = val.Detail;
this.push(res);
}, modifiedArray);
console.log(modifiedArray)
Working Example in Fiddle
You have to assign it in the http call that gets the response
$htpp.get(....).then(function(response){
lang_arr = [];
response.forEach(function(obj){
var item = {obj.keyName : obj.detail};
lang_arr.push(item);
}

Backbone.js - unable to get the model inside the filter function

In my project i am returning a data using filter method, out of filter i am getting the object, but inside the filter getting as undefined...
they way i doing is wrong..? any one guide me please?
my complete code :
var taskListGenerator = function(params){
var taskListPhraseI = {},
column=params.column,
leftSpine=params.leftSpine,
topSpine = params.topSpine;//workspace to phrase one;
taskListPhraseI.model = Backbone.Model.extend({
url : 'data/data.json',
defaults:{
"id" :"id",
"title" :"Title",
"projectName" :"project",
"dueDays" :0,
"dueTime" :0,
"dueDate" :"0-0-0000",
"totalTasks" :0,
"taskCompleted" :0,
"percent" :65,
"taskStatus" :"Assigned",
"jobtype" :"vip",
"username" :"scott.pierce#groupfmg.com",
"notes" :"notes1"
}
});
taskListPhraseI.collection = Backbone.Collection.extend({
model:taskListPhraseI.model,
url : 'data/data.json',
resetWithFilter : function(data,type) {
var filtered = data.models.filter(function (item) {
return item.get("dueDays") === type;
});
return filtered;
}
});
taskListPhraseI.oneView = Backbone.View.extend({
template:$('#boardTemplate').html(),
render:function(){
var temp = _.template(this.template);
return temp(this.model.toJSON());
}
});
taskListPhraseI.allView = Backbone.View.extend({
el:$('.boardHolder'),
events:{
'click span.green' : 'filterIt'
},
initialize:function(){
var that = this;_.bindAll(this);
this.collection = new taskListPhraseI.collection();
this.collection.fetch({success:that.render});
this.on('change:filterType', this.setNewType);
//this.on('reset:filterType', this.setNewType);
},
setNewType:function(){
var newCollection = new taskListPhraseI.collection();
newCollection.fetch({context:this,update:true})
.done(function(){
this.collection.reset(newCollection,{ silent: true })
var values = newCollection.resetWithFilter(newCollection,this.filterType);
this.render(values);
});
},
filterIt:function(e){
this.filterType = parseInt($(e.target).text());
this.trigger('change:filterType');
},
localVariable:{
numElement:0,
modelSize:0,
stepElement:$('.stepValue'),
stepRange : $('.stepRange'),
stepWidth:0,
compoundWidth:0,
viewProter : $('.stepRangeCompound')
},
render:function(data){
this.localVariable.modelSize = this.collection.models.length;
console.log(data) // first time work fine, while it work on click event, show the error
_.each(data.models, function(item){
this.renderBoard(item)
},this);
},
renderBoard:function(item){
var singleView = new taskListPhraseI.oneView({model:item}),
board = this.$el.append(singleView.render()),
newBoard = board.find('.indBoard:last');
this.positionBoards(newBoard);
},
positionBoards:function(tag){
var prop = this.localVariable,
boardWidth = tag.outerWidth(),
boardHeight = tag.outerHeight(),
topVal = prop.numElement % column,
lftVal = Math.floor(prop.numElement / column),
holderWidth = 0;
prop.stepWidth = boardWidth,
prop.compoundWidth = $('.stepRangeCompound').width();
this.$el.css({
height: (boardHeight+topSpine) * column,
width : Math.ceil((prop.numElement+1) / column) * (boardWidth+leftSpine),
});
holderWidth = this.$el.width();
if(holderWidth <= prop.compoundWidth){
$('.stepRange').hide();
}else{
$('.stepRange').show();
}
tag.css({
left:(boardWidth * lftVal) + (lftVal * leftSpine),
top:boardHeight * topVal + (topVal* topSpine),
});
prop.numElement++;
if(prop.modelSize === prop.numElement){
this.initStepScroll();
}
},
initStepScroll:function(){
var prop = this.localVariable,
stepNavi = prop.stepElement,
stepMin = stepNavi.find('.stepMin'),
stepMax = stepNavi.find('.stepMax'),
stepHandler = prop.stepRange,
maxScrollable = this.$el.width() - prop.compoundWidth,
accomadable = Math.floor(prop.viewProter.width() / prop.stepWidth),
showing = accomadable * column <= prop.modelSize ? accomadable * column : prop.modelSize,
startVal = 0,
that = this;
stepMax.text(prop.modelSize);
stepMin.text(showing)
var slideElement = stepHandler.slider({
min:0,
max:maxScrollable,
step:prop.stepWidth,
slide:function(i,ob){
startVal = Math.abs(parseInt(that.$el.css('marginLeft')));
that.$el.css({
marginLeft:-ob.value
});
var currVal = Math.abs(parseInt(that.$el.css('marginLeft')));
var dir = startVal < currVal ? 1 : startVal > currVal ? -1 :'';
showing += dir * column
var update = showing > prop.modelSize ? prop.modelSize : showing;
stepMin.text(update);
}
});
slideElement.find('.ui-slider-handle')
.wrap(
$('<div />').css({
position:'relative',
marginRight:slideElement.find('.ui-slider-handle').width(),
height:'100%'
})
);
}
});
var boards = new taskListPhraseI.allView();
}
Json sample :
{
"id" :1, "title" :"Title1",
"projectName" :"project1", "dueDays":7,
"dueTime":2.45, "dueDate":"12-12-2010",
"totalTasks" :15, "taskCompleted" :10,
"taskStatus" :"Assigned", "jobtype"
:"vip", "username"
:"scott.pierce#groupfmg.com", "notes"
:"notes1"
}
error:
undefined
tasklist.js (line 33)
TypeError: item is undefined
Thanks in advance
i converted my array return from filter in to collection, sending back to collection method like this.. it work correctly
setNewType:function(){
var newCollection = new taskListPhraseI.collection();
newCollection.fetch({context:this,update:true})
.done(function(){
var values = new taskListPhraseI.collection(newCollection.resetWithFilter(newCollection,this.filterType));
// send back to collection to convert array became collections, it solves the issue.
this.render(values);
});
},
thanks all.

Titanium Appcelerator HTTPClient return Array

i want to put the httpclient in a separate class and want to return the array of founded data.
My Code
function ServiceRequest(callback){
var data = [];
var xhr = Titanium.Network.createHTTPClient({
onload: function(e){
//Ti.API.info("Received text: " + this.responseText);
var doc = this.responseXML.documentElement;
var elements = doc.getElementsByTagName("record");
for (var r=0;r<elements.length;r++){
var name = elements.item(r).getElementsByTagName("field").item(3).textContent;
var monteur = elements.item(r).getElementsByTagName("field").item(15).textContent;
var adresse =elements.item(r).getElementsByTagName("field").item(10).textContent;
var ort = elements.item(r).getElementsByTagName("field").item(4).textContent +" - "+ elements.item(r).getElementsByTagName("field").item(5).textContent;
var date = elements.item(r).getElementsByTagName("field").item(8).textContent;
var termin
if (date !="") {
var arrayDate = date.split(".");
var newdate = arrayDate[1]+"."+arrayDate[0]+"."+arrayDate[2];
var temptermin = newdate +" - "+ elements.item(r).getElementsByTagName("field").item(9).textContent;
termin = temptermin;
};
data.push({"name":name,"monteur":monteur,"adresse":adresse,"ort":ort,"termin":termin});
callback( data );
};
},
onerror: function(e){
Ti.API.debug(e.error);
alert(e.error);
}
});
xhr.open("GET","http://theurltomyxml.com",false);
xhr.send();
}
module.exports =ServiceRequest;
the code snippet for my initialization
var ServiceRequest = require('ui/common/ServiceRequest');
request = new ServiceRequest(function(data){
});
Ti.API.info(request);
But the request is null, the array in my onLoad function is filled with data.
How can i wait until the httpRequest is ready than return the data array ?
You can use your custom function for callback like this way onload : callBack create your own callback function or you can put your callback( data ); after your forloop.
for (var r=0;r<elements.length;r++){//==your code here for parsing
}
callback( data );

Resources