1

This is what I am trying to achieve, I am making one call to an api that results in multiple calls based on zip code and radius. Based on population density results could be as few as one result or as many as twenty. The results of this call are returned as arrays of no information to multiple entries. The thing that I need to do is to take the multiple individual arrays and create one array that removes all the empty arrays and appends each individual array into one. the code that currently makes the multiple calls is:

const https = require('https');
const fetch = require('node-fetch');
var zipcodes = require('zipcodes');

var food_truck_zip = '29615'

var userzip = food_truck_zip

var user = zipcodes.lookup(userzip);
//console.log(user);

var rad = zipcodes.radius(userzip,4);

array = rad;
for (var i=0; i<array.length; i++)
    var zipsArray = array;
    for(let i=0;i<zipsArray.length; i++) {
      fetch('https://36245d69.ngrok.io/api/vendor_filter/?zipCode=' + 
      zipsArray[i])
        .then(response => {
         return response.json();
        })
        .then(function handleData(data) {
          var buildOutput = [];
          buildOutput.push(data);
          console.log(JSON.stringify(buildOutput));
        })
        .catch(function handleError(error) {

        });
   };

and the results of the console.logs to buildOutput look like this:

[[]]
[[]]
[[]]
[[{"truckName":"Chuck Truck","locationName":"Butler Springs 
Estate","locationAddress":"Butler Springs Road","beginning":"10:00 
am","ending":"05:00 pm"},{"truckName":"Henry's Hog 
Hauler","locationName":"Strange Brew","locationAddress":"1100 Wade 
Hampton","beginning":"06:30 pm","ending":"08:30 pm"}, 
{"truckName":"Chuck Coffee Crusted Salmon","locationName":"The Home 
Base","locationAddress":"Butler Springs Estates","beginning":"04:30 
pm","ending":"06:00 pm"}]]
[[]]
[[{"truckName":"ThoroughFARE","locationName":"Grateful 
Brew","locationAddress":"800 North Pleasantburg","beginning":"04:30 
pm","ending":"07;00 pm"}]]
[[]]

So the results for this zip code with a radius of 4 miles is seven zip codes of which 2 currently have entries. An help with this would really be appreciated, putting the seven individual calls into one array then removing any zero entries.

Chuck LaPress
  • 278
  • 1
  • 10
  • 18
  • You're shadowing the `i` variable in the outer loop. Better to pick a different variable name such as `j`, or avoid `for` loops entirely and use something like `forEach`, or `map` the requests so you can proceed to `Promise.all`. Also, don't mix `var` and `const` - preferably, always use `const`. – CertainPerformance May 08 '18 at 02:58

1 Answers1

0

Maybe the following will help, your code doesn't make much sense to loop over the same array twice, your inner array is the same as your outer.

function Fail(reason){this.reason=reason;};
const isFail = o => (o&&o.constructor)===Fail;
const isNotFail = o => !isFail(o);

Promise.all(
  rad.map(
    zip =>
      fetch('https://36245d69.ngrok.io/api/vendor_filter/?zipCode=' +
      zip)
      .then(response => {
        return response.json();
      })
      .then(function handleData(data) {
        console.log("got data:",JSON.stringify(data));
        return data.map(
          //add zip to item, your question does not show zip but comment askes
          // for zip to be there
          item=>({...item,zip})
        );
      })
      .catch(function handleError(error) {
        err=>new fail([err,zip])
      })
  )
).then(
  results => {
    console.log(
      "successes:",
      results
        .filter(isNotFail)
        .filter(item=>!!item.length)//remove empty items
        .reduce((result,item)=>result.concat(item))//flatten array of array to one array
    );
    results.filter(isFail).forEach(
      ([error,zip])=>console.log("failed:",zip,"with error:",error)
    )
  }
)
HMR
  • 37,593
  • 24
  • 91
  • 160
  • Just to be clear the first loop creates the api call each zip code in the set radius is different, so this happens on the first loop, 29615 is user base and numbers change as the radius expands. I’m uncertain if you took that into account, this didn’t happen with my code without creating the loop. – Chuck LaPress May 08 '18 at 03:49
  • @ChuckLaPress rad, array and zipArray are all the same in the code you posted. Maybe you are imagining some other code you didn't post or maybe you posted the wrong code but what is in the question doesn't make much sense even with your comment. – HMR May 08 '18 at 03:59
  • I’m sorry @HMR I wasn’t questioning your answer, I was simply saying why I thought I needed to loop twice, I posted my complete code and why I thought it was needed to loop twice. Sorry if I offended you, I really appreciate your answer. Thank you – Chuck LaPress May 08 '18 at 04:15
  • so isFail, and isNotFail operate as the filters, when executing the code I am still logging [] as: got data: [] and successes: [ [], so is there a way in the filter method to eliminate these. thank you again for taking the time to answer. – Chuck LaPress May 08 '18 at 05:00
  • @ChuckLaPress It's not a big deal, please look at the code you posted in the question and try to figure out what it does. Creating user and never use it, creating 3 references to the same array and using it for a nested loop, it just doesn't make much sense. i hope the answer helped you but if it didn't then please update your question with some code that either makes sense or describe what it is you are trying to do. – HMR May 08 '18 at 05:06
  • @ChuckLaPress you could try to console.log `'https://36245d69.ngrok.io/api/vendor_filter/?zipCode=' + zip` open that up in the browser and see what that gives you, my guess is that it gives you "[]" You may also want to console.log each data item and let us know what it is you want with it. Is data an array and you'd like to remove empty ones? – HMR May 08 '18 at 05:09
  • thank you, the answer did clarify a lot of confusion and certainly you are right parts should have been edited as non relevant for this question, to answer the second comment you ask yes the empty arrays are there because a call is made to them, and they contain no data so is there a way to eliminate the empty arrays? so that the only successes are zip codes with data in the array ideally my data would return 1 array that has all successful data arrays appended to it, I'm not sure if this is possible currently the data contains seven arrays 3 with data 4 empty – Chuck LaPress May 08 '18 at 05:33