0
let all_data = []

d3.tsv("https://raw.githubusercontent.com/KingJacker/movies/master/movies.tsv", function(data) {
    all_data.push(data)
});

console.log(all_data) // --> image 1

console.log(all_data[0]) // --> undefined

image 1:

Why does the array return undefined when I use a specific index?

When I defined my array manually it works.

let manual_data = [
    {Name: "Solaris", Year: "2002",Genre: "Drama/Mystery",Length: "2 hours",IMDb: "62%","Rotten Tomatoes": "66%",Metacritic: "65%","liked this film": "64%"},
    {Name: "Toad Road",Year: "2012",Genre: "Drama/Thriller",Length: "1h 16m",IMDb: "50%","Rotten Tomatoes": "75%",Metacritic: "54%","liked this film": "78%"}
]

console.log(manual_data[0]) // works as expected

But of course it isn't the goal to just type out all of my data.

Paolo Mossini
  • 1,064
  • 2
  • 15
  • 23

1 Answers1

1

d3.tsv is asynchronous and uses a callback.. The code you put after the callback will actually run before the callback is called, since the function doesn't block the execution of the code. If you want your code to work, you have to put it inside the callback so the function is guaranteed to finish.

let all_data = []

d3.tsv("https://raw.githubusercontent.com/KingJacker/movies/master/movies.tsv", function(data) {
    all_data.push(data)
    // note that this is inside the callback now
    console.log(all_data)
    console.log(all_data[0])
});
Aplet123
  • 33,825
  • 1
  • 29
  • 55