So I have a List and I am able to filter to find on it which works fine for reducing the list to what I am looking for.
However, let's say I just want to get back an array of numbers, not a List, back from my search, something like:
var found = campaignTimelineBoardTemplatesModels.map((campaignTime) => {
if (campaignTime.getId() == num)
return Math.random();
});
The problem is that found is now still a List, and 2, is that I have a undefined members in this List as it seems to hold the same size as my original List.
So Map didn't do it.
All I am trying to do is get back a simple list of pure numbers that match a condition back as a pure array.
Is it possible?
Thanks,
Sean
found it, magic of reduce:
var IDs = campaignTimelineBoardTemplatesModels.reduce((result,campaignTimelineBoardTemplatesModel: CampaignTimelineBoardTemplatesModel)=>{
if (campaignTimelineBoardTemplatesModel.getCampaignTimelineId() == i_campaign_timeline_id)
result.push(campaignTimelineBoardTemplatesModel.getCampaignTimelineId());
return result;
},[])
Related
I am trying to count the number of rows in an advanceddatagrid
I need a function which could count all item with or without filterFunction.
I tried some solution but none works. The best that I found, is to expand all items and use a cursor for looping.
But, when we have a lot of data, expanding all is not a good solution.
Do you have an idea on how to do that ?
Thank you
The only way I came up was investigating dataProvider
// current not expanded data row lenght
grid.dataProvider.lenght;
// expanded length
// I assume you use xml as your data provider
// then you can count it like this
xmlListTotalSize(new XMLList(grid.dataProvider.source.source));
// or with casts
xmlListTotalSize(new XMLList((IHierarchicalCollectionView(view.grid.dataProvider).source as HierarchicalData).source));
and xmllist traversal function might look something like this:
private static function xmlListTotalSize(x:XMLList):int
{
var i:int = x.length();
for each(var xChild:XML in x.children())
i += xmlListTotalSize(xChild.children());
return i;
}
I generally find indexOf very useful, to get an index directly, and not writing 3-4 lines of for loop to get a match.
Is there any similar function, say like indicesOf , to get an array of all possible matches ?
Or may be having a different name, but acts as a shortcut as beautifully as "indexOf" ?
As you don't mind creating a new Array, you can use the filter() function - it executes a function on each item of the array, then returns a new Array with the items that return true:
// our comparison function
function myCompFunction( element:*, index:int, array:Array ):Boolean
{
return ( element > 10 );
}
var ar:Array = [5,10,15,20];
var ar2:Array = ar.filter( myCompFunction ); // ar2 is now [15,20]
It's not exactly indicies, but then again, you don't need to dereference your objects.
NOTE: because it's calling a function on each element, looping through the array yourself will still be quicker
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/Array.html#filter()
Unfortunately, there is not such shortcut. indexOf works for only one item, and there is no alternative for multiple items.
The solutions are obvious - iterate over the entire array or use some kind of sort on the array. Maybe there are other methods, but they are almost the same - loop through everything and check. Sorry to say it, but that's the way it is :)
I am making a pretty neat quiz-game in flashCC right now and I definitely need your help.
My skills are more on the design then the programming side. So to many of you this might seem a baby question (and asked many times before) but from all the answers I saw so far, I couldn't get any results for my project.
So here is the thing :
I need the EXACT script for creating an array (with movieclips inside? or instance names of mcs? How does this even work?)
and a method, to pick a random element of this array without repeats until the "game is over".
Paul
The easiest way to pick a random element from an array without repeating is to first sort the array with a "random" function, then pop or shift items out of it until the array is empty.
Let's say you have an array of items which can be filled with either instances or instance names, you've chosen instance names: :
var FirstArray:Array = ["blau", "orange", "green"];
Now, you'll need a random sort function:
// you do not need to modify this function in any way.
// the Array.sort method accepts a function that takes in 2 objects and returns an int
// this function has been written to comply with that
function randomSort(a:Object, b:Object):int
{
return Math.random() > .5 ? -1 : 1;
}
The way a sort function normally works is it compares two objects and returns -1 if the first item precedes the second item, 1 if the opposite is true, and 0 if they are the same.
So what we're doing in the function above is returning -1 or 1 randomly. This should get the array all jumbled up when you call:
FirstArray.sort(randomSort);
Now that the array is randomly sorted, you can begin pulling items from it like so:
if(FirstArray.length) // make sure there's at least one item in there
{
// since you are using instance names, you'll need to use that to grab a reference to the actual instance:
var currentQuizItem:MovieClip = this[FirstArray.pop()];
// if you had filled your array with the actual instances instead, you would just be assigning FirstArray.pop() to currentQuizItem
// every time you call pop on an array, you're removing the last item
// this will ensure that you won't repeat any items
// do what you need to do with your MovieClip here
}
else
{
// if there aren't any items left, the game is over
}
When strung together, the above code should be enough to get you up and running.
You could try something like:
var array:Array = [1, 2, 3, 4, 5];
var shuffledArray:Array = [];
while (array.length > 0)
{
shuffledArray.push(array.splice(Math.round(Math.random() * (array.length - 1)), 1)[0]);
}
trace('shuffledArray: ', shuffledArray, '\nrandom item: ', shuffledArray[0]);
i am just not able to read a csv file .I want to display a graph for it.
I am getting error:
TypeError: n is undefined
please help me out!!
d3.csv("example.csv", function(dataset){
var svg=d3.select("body").append("svg").attr("width",w).attr("height",h);
var xScale=d3.scale.ordinal().domain(d3.range(dataset.length)).rangeRoundBands([0,w],0.05);
var yScale=d3.scale.linear().domain([0,d3.max(dataset.value)]).range([0,h]);
svg.selectAll("rect").data(dataset).enter().append("rect").attr({x:function(d,i) {return xScale(i);}, y:function(d){
return h-yScale(d);}, width:xScale.rangeBand(),height:function(d){return yScale(d);},fill:function(d){return "rgb(0,0,"+(d.value*10)+")";}});
d3.select("svg").selectAll("text").data(dataset).enter().append("text").text(function(d) {return d.value;}).attr("x",function(d,i){
return xScale(i)+xScale.rangeBand()/2;}).attr("y",function(d){return h-yScale(d)+14;}).attr("font-family","sans-serif").attr("font-size","10px").attr
("fill","white").attr("text-anchor","middle");
d3.select("p").on("click",function(){
var numValues=dataset.length;
dataset=[];
for(var i=0;i<numValues;i++)
{var newNumber=Math.floor(Math.random()*25);
dataset.push(newNumber,newNumber);
}
yScale.domain([0,d3.max(dataset)]);
svg.selectAll("rect").data(dataset).transition().delay(function(d,i){return i/dataset.length*1000;})
.duration(500).attr("y",function(d){return h-yScale(d); }).attr("height",function(d) {return yScale(d);}).attr("fill",function(d){
return "rgb(0,0,"+(d.value*10)+")";});
svg.selectAll("text").data(dataset).transition().delay(function(d,i){return i/dataset.length*1000;}).duration(500).text(function(d){return d.value;})
.attr("x",function(d,i){return xScale(i)+xScale.rangeBand()/2;}).attr("y",function(d) {return h-yScale(d)+14;})
.attr("font-family","sans-serif").attr("font- size","10px").attr("fill","white").attr("text-anchor","middle")
;});
});
here is my csv file
names,value
john,78
brad,105
amber,103
james,2
dean,74
pat,45
matt,6
andrew,18
ashley,15
As mentioned by cuckovic there are quite a few errors in your code, not to mention that you seem to be using different styles to achieve similar things which is confusing. Anyway there are 3 fundamental things that are casuing you trouble, the first is your dataset. The value column of the csv is being read as a string. You need to convert it to a number by:
dataset.forEach(function (d,i) {
d.value = +d.value;
});
The next issue you have is the yScale where you have set the range to .range([0,h]);. This is the wrong way round for an svg viewport in which the y direction starts from top and increases towards the bottom. So you need to swap the 0 and h around in the range.
The next thing to address is the difference between d and d.value. When you bind data through the data() operator you are generally binding an array. In this case it is an array of objects. So after you have bound the data, d refers to each element of that array which in this case is an object containing a name and a value. This can be seen if you console.log your dataset. When d is passed to yScale it doesn't know what to do with it as it is not a number, what you really want to do is to pass d.value to yScale. So replace your d's with d.value.
Finally, the last part of your code starting at d3.select("p") does not seem to add anything.
I'd recommend reading Scott Murray's tutorials, particularly this one if you haven't already.
Hmmm, maybe someone can help me out here or point me in the right direction , as i have been banging my head against the wall for a number of days now and dont seem to be gettin anywhere useful.
(and admittedly i'm pretty new with regards to json,objects, google visulization etc)
essentially, i am running 3 different queries on the same page against 3 different fusion tables, which in return are supposed to return an array of 3 different xets of markers.
all is fine, when i run the queries individually and make an array of the markers .
however, running the 3 queries on the same page, i can't seem to find a way to identify the query in the response function.
any hints much appreciated. and i'll be happy to provide more info if needed (tried to get rid of some unneccessary stuff)
this is what i have. thanks
a) calling the function "setFusionData()" with all relevant vars. something like setFusionData("'LatLng','name'", 2729461);
(this is calles 3 times with different variables)
function setFusionData(selColumns,tableId) {
/****
an actual query example is this:
http://www.google.com/fusiontables/gvizdata?tqx=reqId:1234&tq="select+'LatLng','name'+from+2729461"
****/
var query = new google.visualization.Query(
'http://www.google.com/fusiontables/gvizdata?tqx=reqId:1234&tq='+ encodeURIComponent("SELECT "+selColumns+" FROM "+tableId+"")
);
query.send(getFusionData); //do something with the response
}
function getFusionData(response) {
/**
here, is the problem as i need to get the table id or reqId or anything that is uniquely passed on from "setFusionData" above
also something like
alert(JSON.stringify(response)) does not return any reqId or table id either
***/
/*return rows/columns and add values to an array of markers***/
var numRows = response.getDataTable().getNumberOfRows();
var numCols = response.getDataTable().getNumberOfColumns();
for (i = 0; i < numRows; i++) {
/* add markers to array etc this works fine***/
}
}
i also tried something like this:
function setFusionData(selColumns,tableId) {
......
query.send(getFusionData({reqId:tableId}));
}
function getFusionData(response) {
alert(response['reqId']);//returns tableId. but how do i get the tableData ?
}
with wich i can get the reqId, but not the table*Data*. So I am only able to get either id or data :(
----edit----------------
after messing around a bit more (see below) it appears that the key/value pairs that get returned when typing the query into the browser directly are different than what gets returned by the call from the script...i.e the following
http ://www.google.com/fusiontables/gvizdata?tqx=reqId:1234&tq="select+'LatLng','name'+from+2729461"
typed directly into the browser bar will return
version:'0.5',reqId:'1234',status:'ok',table etc
however, calling the same from within the script returns something like
{
"rj":"0.5","ef":"ok","pb":[],"qb":[],"h":"{"cols":
[{"id":"col2","label":"LatLng","type":"string"},{"id":"col1","label":"name","type":"string"}],
"rows":
[{"c":[{"v":"47.20572,12.70414"},
{"v":"Hohe Tauern"}]},{"c":[{"v":"47.5530395,12.925611"},{"v":"Berchtesgaden"}]},{"c":[{"v":"47.5585405,14.61887"},{"v":"Gesu00e4use"}]}],
"p":{"totalrows":3}
}"
}
, so no 'reqId' but only some cryptic keys (without one that looks like the reqId either)...... anyone any idea why that would/could be ?
Sometimes you can figure it out by just looking at the JSON response, your sample request returns:
google.visualization.Query.setResponse({
version:'0.5',
reqId:'1234',
status:'ok',
table: {
...
}
})
You already got response.reqId to identify which request is this the response for, now you can use response.table to create a new DataTable instance:
var dt = new google.visualization.DataTable(response.table);
Or, since you have multiple tables, put then in an array indexed with the reqId
tables[response.reqId] = new google.visualization.DataTable(response.table);
You'd do var tables = new Array() before calling setFusionData() for the first time.