I have a piece of code in an app that I am having difficulty pushing items to an empty array. At the beginning of this section, I created some empty array variables.
var sumPOP = [];
var sumRACE = [];
var sumLANG = [];
var sumINCOME = [];
I am going to then iterate through some selected data, so I have a for loop. Within this loop, I am making a call to an api (I know, it's GIS. That's irrelevant. Just pretend it's an ajax call) to retrieve some data. I am able to console.log() the data and it shows up correctly. I then want to push that data (each item in the loop) to the before mentioned empty arrays. Then to test that the array has been populated, I console.log() the array, both within the loop and outside it. My problem is that nothing shows when I console.log the array. Why is the data not getting pushed outside the array? Note: console.log(sumPOP) run within the call function(esriRequest) does show the items pushed to the array:
for (var i=0;i<results.features.length;i++){
...
esriRequest({
url:"https://api.census.gov/data/2016/acs/acs5",
content:{
get: 'NAME,B01003_001E,B02001_001E,B06007_001E,B06010_001E',
for: `tract:${ACS_TRCT}`,
in: [`state:${ACS_ST}`,`county:${ACS_CNTY}`]
},
handleAs:'json',
timeout:15000
}).then(function(resp){
result = resp[1];
POP = result[1];
console.log(POP);
sumPOP.push(POP);
RACE = result[2];
LANG = result[3];
INCOME = result[4];
console.log('POP: ' + POP + ', RACE: ' + RACE + ', LANG: '+ LANG + ', INCOME: ' + INCOME);
}, function(error){
alert("Data failed" + error.message);
});
console.log('POP: ' + sumPOP);
...
}
console.log('POP: ' + sumPOP);
Additional information: My eventual goal is to get the final array after the selected data has been iterated through and summarize it; or rather, add it together. My expected array results would be sumPOP = [143, 0, 29, 546, 99];
I want apply a function (also outside the loop) to do this:
newSum = function(category) {
let nAn = n => isNaN(n) ? 0 : n; //control for nonNumbers
return category.reduce((a, b) => nAn(a) + nAn(b))
};
...and then run popTotal = newSum(sumPOP); to get the total.