Angular: Posting Data to a Table with a loop and giving a problem when posting the i of the loop into the table - mysql

Good day,
I am trying to get data into a table, with the tour_id and every single media_id (the station_id i am getting from somewhere else), the ordernumber is what is giving me a headache:
I am trying to get every station one number for every media i am posting.
For example:
station 1 has 2 medias
and station 2 has 3
then the odernumbers should be like this: 0, 0, 1, 1, 1
I am using the following Code at this moment:
for(var i = 0; i < this.currentStations.length; i++){
this.http.get("http://localhost:3000/mediasforstation/" + this.currentStations[i].id).subscribe((res) => {
medias = res;
for (var j = 0; j < medias.length; j++){
this.http.post("http://localhost:3000/posttourstations",
{"tour_id": id, "media_id": medias[j].id, "ordernumber": i}).subscribe(function(res) {
console.log(res);
}.bind(this));
}
});
}
Everything but the ordernumber works, however, the ordernumber always takes the number of stations involved, in our example above it would be 2.
How do I fix this?
Thank you very much for your help.

As I understand, you need to keep the index value. The type of variable i is var which is function scoped. Within outer loop, you are calling an API that returns some response, meanwhile the value of i is updated and for next index/counter, the API call has been sent. When you get response from API calls, you get the value of i where the outer loop has been called of.
In other words, you need to understand the difference between var and let. Your problem can be solved by replacing
for(var i=0;...)
with
for(let i=0;...)
Here's providing you the sample code.
//block scoped - retains value of i
for (let i=0;i<10;i++){
this.http.get('https://jsonplaceholder.typicode.com/users').subscribe(res=>{
for(var j=0;j<5;j++){
console.log(`i=>${i}`)
}
})
}
//function scoped - gets updated value of i
for (var i=0;i<10;i++){
http.get('https://jsonplaceholder.typicode.com/users').subscribe(res=>{
for(var j=0;j<5;j++){
console.log(`i=>${i}`)
}
})
}

Related

How to render more than X elements in react? (Performance)

I have a huge component that can receive a start and end date, plus some floors numbers, and based on these numbers, it generates a table, something like the below image.
Example of this table:
The problem is, how to make this table generate faster?
To generate the floors I use a for a loop.
JavaScript code:
for (let i = 0; i < section.floorQuantity; i++) {
floors.push(i + 1)
}
and for each day, I generate a column with the number of floors as cells (divs).
you can use "useMemo" to cache the same computation and it's result change when input data changes
const computeExpensiveValue=(inputs)=>{
//do something
return result
}
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);

dc.js crossfilter without reduce

Is crossfilter manipulating my data?
Background
I have performed all the processing I need server side and just want to graph exactly what comes down the json pipe. So far I've get the graph working exactly how I want it to except for it seems my data is being manipulated.
Here's my crossfilter code:
ndx = crossfilter(rData);
runDimension = ndx.dimension(function (d) { return [+d.series, +d.norm_1]; });
runGroup = runDimension.group();
runGroup.reduceSum(function (d) { return d.value;});
Note: norm_1 is unique
Issues
Basically I'm noticing two issues:
I know for a fact that all my data will be between -1 and 1 (I've run several checks to test this), BUT when graphing it I see it dips down to -1.4 in some places.
My server sends exactly 1000 rows of data, but by breakpointing some of the dc.js code I can see it's only graphing 752 rows.
More Evidence
On my chart I've set the valueAccessor and added some checks to test the values going out of bounds, and I can see very clearly it goes out:
.valueAccessor(function (d) {
if (d.value > 1 || d.value < -1) {
console.log(d);
}
return d.value;
})
The data from the server requires a small amount formatting before going into crossfilter (it comes down as a table and needs to be split into series objects). I used this as an opportunity to test whether the data goes out of bounds, and I can see clearly it stays within bounds:
for (var i = 0; i < $scope.remoteData.rows.length; i++) {
for (var j = 0; j < $scope.remoteData.labels.length; j++) {
var label = $scope.remoteData.labels[j];
var value = $scope.remoteData.rows[i][label];
if (value > 1 || value < -1) {
console.log({
label: label,
i: i,
series: j,
norm_1: $scope.remoteData.rows[i].norm_1,
value: value,
});
}
rData.push({
series: j,
norm_1: $scope.remoteData.rows[i].norm_1,
value: value
})
}
}
Discussion
I suspect my problems have something to do with:
runGroup.reduceSum(function (d) { return d.value;});
Is this function adding together certain data points?
Sounds like you have some rows for which [+d.series, +d.norm_1] is not unique. And yes any rows with the same key will be added with reduceSum.
I'd suggest making your dimension key be something that's really unique.
If you don't have a unique key, with a little more work you could use the array indices themselves as the dimension key. It will mean you have to use both key and value accessors everywhere to look back in the original array.
Something like:
ndx = crossfilter(d3.range(0, rData.length));
runDimension = ndx.dimension(function(d) { return d; })
runGroup = runDimension.group().reduceSum(function(d) {
return rData[d].value;
})
chart.keyAccessor(function(kv) { return rData[kv.key].x; })
.valueAccessor(function(kv) { return rData[kv.key].y; })

How do i make my pickNum array just one index instead of 3 different indexes.

this will random my numPool and push the random three numbers to my array called pickNum. I need that pickeNum to be just one index instead of three indexes. Thanks and i will appreciate any help thanks.
var numPool:Array = [1,2,3];
var pickNum:Array = [];
var randomCount:Number = 3;
var r:Number;
for (var i = 0; i < randomCount; i++)
{
r = Math.floor(Math.random() * numPool.length);
pickNum[pickNum.length] = numPool.splice(r,1);
}
trace("Number Picked " + pickNum);
Can't say I completely understand what you are saying, but the issue with the code above is that splice returns an Array containing the values that were spliced from the array. Also, would be easiest to just do a push. So the proper line for getting that value and pushing it into the pickNum array would be :
pickNum.push(numPool.splice(r,1).pop());
And if you are saying that you want only 1 random number from the pool, then why do you need a loop ?

Razor: adding dynamic values together

I have a set of values that are generated dynamically with a foreach loop, how can I add these into one value?
For instance, say I have a site where each node has a number associated with it. How can I add all these numbers together? So far I've figured it'd be something similar to the following, where the value of 'node.aNumberValue' is added to the next one, and so on:
#foreach (var x in nodes){
var total = node.aNumberValue + node.aNumberValue (etc...);
<p>#total</p>
}
This is what you want, I think:
int total = 0;
#foreach (var x in nodes)
{
total += x.aNumberValue;
}
<p>#total</p>
Or even better, just:
<p>#nodes.Sum(x => x.aNumberValue)</p>

Difficulty outputting an array of indexes from an existing array consisting of strings

So I am trying to create a function that searches through an array based on a searchTerm. If the elements within the array have the searchTerm in it, it should output ALL of indexes inside of MyArray[];.
I hope I have explained clearly, thanks in advance.
Here's a corrected version:
var colours = ["I like the colour red", "I hate the colour yellow", "I love the colour blue"];
function myFunction(colours, searchTerm) {
var myArray = [];
searchTerm = searchTerm.toLowerCase();
for (var i = 0; i < colours.length; i++) {
if (colours[i].toLowerCase().indexOf(searchTerm) >= 0) {
myArray.push(i);
}
}
return myArray;
}
alert(myFunction(colours,"colour")) //Should return indexes 0,1,2 in myArray
And a working demo here: http://jsfiddle.net/jfriend00/GDM9R/.
I had to fix a lot of issues:
You weren't adding results to myArray properly.
You weren't adding the index to myArray.
You weren't testing the results of .indexOf() properly (it returns -1 when no match).
You were iterating over the length of the search phrase, not the number of items in the array.
You didn't declare i as a local variable so it was an implicit global variable.
myArray = colours[i] does not append to the array.
myArray.push(a);