Issues with populating arrays from csv(dsv) parsing - javascript

I am quite new to javascript, basically using it for the first time to write a histogram plotter application. My issue is, I am importing a data file and ideally sending (some of) the entries into an array. Problem is that once I do that, I have troubles accessing the entries in my array.
How could I fix that? Posting the code below in case it helps.
Thank you!
let filename = 'uploads/testdata.dat';
const data_e = new Array();
d3.dsv(" ",filename, (event)=>{
data_e.push(event.mass);
return data_e
})
console.log(data_e);
Which outputs
Array []
​
0: "734.770828169"
​
1: "85.0912893849"
​
2: "87.383924186"
​
...
However if I wanna get a value:
console.log(data_e[0]) //output: undefined
Edit1: the values I'm pushing are in console.log(event.mass).
output:
734.770828169 analyzer.php:19:12
85.0912893849 analyzer.php:19:12
87.383924186 analyzer.php:19:12
(...)
Edit2: If I call console.log(data_e) inside the dsv function I get a line for each iteration while my array gets filled, ending with
Array(7178) [ "734.770828169", "85.0912893849", "87.383924186", "1274.99805502", "91.5349415148", "80.2766459668", "1396.69489276", "91.5584443363", "94.52017453", "1582.29197222", … ]
Which is, indeed the object I want to get. But what if I want to carry that outside the function dsv(), so that I get the same output as above?
Edit3: Calling console.log(JSON.stringify(event.mass)) gives:
again, one line for each 'iteration' (I think), and it makes sense. I just want to use the full array outside that function (or maybe it's just a silly thing to do .-.)
"734.770828169" analyzer.php:19:12
"85.0912893849" analyzer.php:19:12
"87.383924186" analyzer.php:19:12
"1274.99805502" analyzer.php:19:12
(...)

Do not use return inside the loop, because you then leave it immediately. Whatsmore, I think d3.dsv() is an asynchronous function. Means your console log outside this method must return undefined as Javascript does not wait for d3.dsv() to finish. And your Array data_e is currently undefined.
let data_e = new Array();
Instantiate it this way and you'll see, that console.log() will output [] instead of undefined.
let data_e = [];
d3.dsv(" ",filename, (event)=>{
// your code
})
console.log(data_e);
Actually, I could not find a manual about how to get a trigger when d3.dsv() is finished. But fo the start try it this way. It's not perfect but it's only supposed to show you that it actually works;
let filename = 'uploads/testdata.dat';
const data_e = new Array();
// run the filter
d3.dsv(" ",filename, (event)=>{
data_e.push(event.mass);
})
// wait 2 seconds, then show the array in the console
setTimeout( () => {
console.log(data_e);
}, 2000);

Related

The below 2 sets of codes, one of them works and the other does not. can someone help me undertand why

toDoList is an array with some objects with propeties
This one does not work. It returns undefined.
const showToDo = toDoList.filter((todo)=>todo.isDone === true);
const showToDoTitle = showToDo.forEach(todo=>todo.title);
console.log(showToDoTitle);
This one works
const showToDo = toDoList.filter((todo)=>todo.isDone === true);
showToDoTitle = showToDo.forEach(todo=>console.log(todo.title));
.forEach doesn't return anything.
The second one works because console.log() prints the title within the .forEach function.
If you were to add console.log(showToDoTitle) in the second example, you'd also get a undefined printed.

Javascript isn't setting the Array

I am not getting any errors. When you look at the console.log()'s outputs, the first one gives me the array, and when I open up the 2nd one, it says the array is empty! It's almost as if it was never set. The array I'm checking for is .axes.
I can directly access it, but then I can't see it when I expand the object.
This is for the most important thing in my life and the universe is trying to stop me.
for(i=0; i<$.count; i+=1){
h = chain[i];
h.axes = [ chain[0] ];
if (i==3){
console.log('Direct_AXES',h.axes);
console.log('Direct_H',h);
}
chain[0].dna.push(h);
}
As far as I can help you. This works like a charm.
var chain = [{},{},{},{},{}];
for(i=0;i<chain.length;i+=1){
h = chain[i];
h.axes = [ chain[0] ];
if (i==3){
console.log('Direct_AXES',h.axes);
console.log('Direct_H',h);
}
// chain[0].dna.push(h);
}
I added an array with four empty objects (so the code would somehow run). And I commented the last line of the loop because obviously I would run into an error.
Everything is working fine. So the conclusion here is that there is an error in the part you didn't post, because everything is working as expected.
Both logs do print the array and the whole object h containing the axes array.

Difference between js objects constructed in different ways

What is the difference between js objects created in this way? :
var js = {};
js.first = "blah";
js.second = something;
vs:
var js {
first : "blah",
second: something
}
In chrome inspector I don't see any problem. I've problem when passing js variable (first example) to socket.emit which gives me empty object in first case but works fine in the second example.
I'm confused.
Reference: https://stackoverflow.com/questions/20828860/why-cannot-i-pass-object-via-node-js-emit
There is absolutely no difference between these 2 ways of creating an new object.
First example just shows how dynamically you can add new keys and values to existing object.
if you try to compare them with == you will get false, but even if you create 2 objects similar way, you will get false as well...
var js = {
first : "blah",
second: something
}
var js2 = {
first : "blah",
second: something
}
js == js2 //false
so it seems to be some browser/node bug, if it's giving you empty object. Maybe parser bug? hard to say. But there is no actual difference

Apply function javascript looping extra

I'm a newbie to Javascript and created a sample function to test the apply function of the javascript.
I need couple of clarification on this code,
value -x will take the first array ['val1','val2'] but just wondering it substitutes to (this,x)..
2.I see a 3 items being printed in the console.log, the last item being - undefined, undefined, What that happends
var dummyfunction1 = function(val1,val2){
console.log(array1,array2);
};
[['val1','val2'],['val3','val4']].forEach(function(x){
dummyfunction1.apply(this,x);
});
dummyfunction1()
There are a couple of issues here.
dummyfunction1 is using variable that are undefined in the body. It should be this:
var dummyfunction1 = function(val1,val2){
console.log(val1,val2);
};
The last line dummyfunction1() is making an additional call to the dummyfunction1 with no parameters. This is the undefined undefined you are seeing.
The full code should be this:
var dummyfunction1 = function(val1,val2){
console.log(val1,val2);
};
// this will automatically be run, no need to call dummyfunction1 on your own after this
[['val1','val2'],['val3','val4']].forEach(function(x){
dummyfunction1.apply(this,x);
});

Bug in console.log? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Is Chrome's JavaScript console lazy about evaluating arrays?
I try the following code:
var myList = new Object();
var item = new Object();
item.text = "item-1";
myList[3] = item;
console.log(myList);
console.log(myList[3].text);
// Assign another object to the same entry
var item2 = new Object();
item2.text = "item-2";
myList[3] = item2;
console.log(myList);
console.log(myList[3].text);
The result is quite odd:
* Object
* 3: Object
text: "item-2"
item-1
* Object
* 3: Object
text: "item-2"
item-2
BUT - if i execute the second part after some time (using setTimeout), and unfold the first object, I get it right, i.e.:
* Object
* 3: Object
text: "item-1"
item-1
* Object
* 3: Object
text: "item-2"
item-2
I find it important to share it, since I think one can waste a lot of time trying to understand what's wrong in his code.
And if somebody has some reference to an open bug or something - please reply this ticket.
Thanks!
My view is that this is a horrendously irritating 'feature' that I really wish I could turn off, it makes debugging a nightmare, not knowing at which point in time something may have updated an object, whilst trying to establish exact object state at a give point in the code. The feature could be useful for 'watch points' etc, but not in something called a 'LOG' (the clue is in the name).
Consider this code fragment:
var person = {'name':'Tom'};
console.log( person); //output the entire object variable
person.name = 'Thomas';
//the output is an object, whose 'name' value is 'Thomas', even though the log statement was placed before the value was changed to 'Thomas'.
AND THEN:
var person = {'name':'Tom'};
console.log( person.name); //changed to output a string variable
person.name = 'Thomas';
//the output here, however, has not dynamically updated and correctly outputs 'Tom'
this is a known bug (50316) that gets reported again and again because people don't take a look at the bugtracker before reporting:
78325
94887
105559
107828
111020
131124
sadly, theres no information about if/when this will get solved. until that moment, you'll need to clone objects before passing them to console.log().
Sounds to me more like a race condition than anything else. Since you are only passing a reference to console.log(), the value it refers it has likely changed value by the time it is actually logged. Then when you use setTimeout(), the value changes after it has been logged. Instead of passing a reference to console.log(), pass a clone of the value.
This is a known problem/feature with the console log in some browsers.
When you log something, it may not immediately be turned into text format. If the log stores a reference to the object that you log, it will be turned into text format when it's actually shown in the log.
This has the advantage that logging something has a very small impact on performance, until you actually open the log window to show the log.
Even if you have the log window open while you run the code, there is no updates happening while your function is running (as Javascript is single threaded), so the console window will show the values as they are at the end of the function, when the window is updated.
I have done some experiments with this "problem" on the latest version of Chrome 20.0.1132.57 m.To summarize the key points :-
console.log() prints a reference to the object with as "> Object" when the code is executed
The state of the object when you click on the triangle is displayed, irrespective of the line of code where the console.log() is executed
If you want to print the object in its current state, print a clone console.log(JSON.parse(JSON.stringify(obj)));
You could use this bit of code to test this on your own browser:
window.onload = function() {chto = {a : 10, b : 20};
console.log('Open this object after 5 seconds')
console.log(chto);
console.log('Open this object before 5 seconds')
console.log(chto);
console.log('Console of the cloned object')
console.log(JSON.parse(JSON.stringify(chto)));
setTimeout(function(){ console.log('5 seconds up'); chto['b'] = 30; },5000 ) ; };

Categories

Resources