Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

176
Views
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.

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.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

you can simply use map.

.then((res) => {
  console.log(res); // output = [ {response}, {response} ]    
  let everyDataArray = res.map(item => item.response);
})
about 4 years ago · Juan Pablo Isaza Report

0

Your code could look something like the following:

.then((res) => {
  let everyDataArray = res.reduce((a,c)=>(a.push(...c.response),a),[]);
  // ...
  console.log(everyDataArray);
})

I used .reduce() instead of .map() as the resulting array will be of different length compared to the input array.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!