i want to sort fetched data via estimated population values. But when i fetch the data and map the names and numbers objects to a new array, i can't even access a single object in the array.
Already tried mapping/converting it with lodash, Array.from(), copying with spread operator,...
Can please someone explain me why? Thanks.
Code:
d3 = require("d3")
_ = require("lodash")
const countries = []
const data = d3.tsv("https://cdn.jsdelivr.net/npm/world-atlas@1/world/110m.tsv")
.then(d => d.map( c => {
countries.push({
name: c.name,
pop_est: +c.pop_est
})
return countries
}))
console.log(countries) // --> i get the array of objects
let a = countries[0]
console.log(a) // undefined
console.log(countries.sort((a, b) => b.pop_est - a.pop_est)) // doesn´t sort
Console output:
[]
0: {name: "Kosovo", pop_est: 1804838}
1: {name: "Somaliland", pop_est: 3500000}
2: {name: "N. Cyprus", pop_est: 265100}
3: {name: "Afghanistan", pop_est: 28400000}
4: {name: "Angola", pop_est: 12799293}
5: {name: "Albania", pop_est: 3639453}
6: {name: "United Arab Emirates", pop_est: 4798491}
7: {name: "Argentina", pop_est: 40913584}
8: {name: "Armenia", pop_est: 2967004}
9: {name: "Antarctica", pop_est: 3802}
10: {name: "Fr. S. Antarctic Lands", pop_est: 140}
undefined
0: {name: "Kosovo", pop_est: 1804838}
1: {name: "Somaliland", pop_est: 3500000}
2: {name: "N. Cyprus", pop_est: 265100}
3: {name: "Afghanistan", pop_est: 28400000}
4: {name: "Angola", pop_est: 12799293}
5: {name: "Albania", pop_est: 3639453}
6: {name: "United Arab Emirates", pop_est: 4798491}
7: {name: "Argentina", pop_est: 40913584}
8: {name: "Armenia", pop_est: 2967004}
9: {name: "Antarctica", pop_est: 3802}
10: {name: "Fr. S. Antarctic Lands", pop_est: 140}
It looks like an issue regarding JavaScript
hoisting
and being single threaded by nature.you need to add your code inside of your callback
.then
in javascript is a promise you'll want to read about those