Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I Improve my logic by using forEach, not for loop in Javascript

Please check my code first

I used axios.all (GET method).

.then((res) => {
  let everyDataArray = [];
  
  console.log(res); // output = [ {response}, {response} ]    

  for(let i=0; i < res.length; i++) {
    everyDataArray.push(...res[i].response)
  }
})

Right now, I’m using for loop for combining all the responses to an array.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

However, What I’m trying to do is using forEach, not for.

I have checked https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach ,

but still working on how. Thank you.

>Solution :

Really what you want is to use map (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) because you want to transform one array into another.

To be clear, forEach is for the case when you want to apply a function to each item to use for side effects (like printing), rather than collecting the return values.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading