0

Im trying accept user input and then if it matches the first value in a row of my csv push that entire row to an array.

I have a csv that looks like this.

City,Lat,Lon,Date
Seattle,47.6,122.3,2015 06 03
Spokane, 47.65, 117.42,2015 06 04

I accept user input like this.

var city = window.prompt("Which city are looking for",);
console.log(city);

Then if the city the user entered matches a city in the csv I want to push it to a new array. Here is the code I wrote for it, but its not quite working.

d3.csv("./some.csv", function(data) {
var lst = [];

for (var i = 0; i < data.length; i++){
if (data.City[i] == 'city') {
lst.push(data[i]);
}
console.log(lst);
}
});

My desired output would look something like this.

[['Seattle',47.6,122.3,2015 06 03],
 ['Seattle',47.6,122.3,2015 06 05]]

Any suggestions would be greatly appreciated.

SAMO
  • 458
  • 1
  • 3
  • 20

1 Answers1

0

I can see several problems.

if (data.City[i] == 'city') {

data is an array, each entry of which is an object with properties with the same names as the column heads. So, instead of data.City[i] you want data[i].City.

Also you are comparing the result with the string literal 'city' instead of the variable city.

Finally you should probably use === to avoid confusing results.

So this line should probably read:

if (data[i].City === city) {

The other thing is the data structure returned by D3 does not match what you are expecting. Instead of:

[['Seattle',47.6,122.3,2015 06 03]]

you will get

[ { City: 'Seattle', Lat: 47.6, Lon: 122.3, Date: '2015 06 03' } ]

If that is a problem for you, you could consider using the d3.csv.parseRows method which returns the data in the form you are expecting. In that case you will need to adapt the comparison line accordingly.

harmic
  • 28,606
  • 5
  • 67
  • 91
  • Oh the 'city' was a silly mistake on my part, but thanks for the suggestions. JS just kind of confuses me. d3.csv.parseRows is exactly what I'm looking for! Thanks so much! – SAMO Jul 21 '15 at 00:46