Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

46
Views
Why forEach won't loop through the entire Array?

When I only use console.log() inside the forEach method it logs all the Array elements, but when I use the .push(array.pop()) inside it, it stops at some of the elements?

const sentence = ['sense.','make', 'all', 'will', 'This'];

function reverseArray(array) {
   debugger;
   let newArray = [];

   array.forEach((arr) => {
     newArray.push(array.pop())
     console.log(arr) 
   })

  return newArray;
}

console.log(reverseArray(sentence))
// RESULT [
//  "This",
//  "will",
//  "all"
// ]

But here it works

const sentence = ['sense.','make', 'all', 'will', 'This'];

function reverseArray(array) {
   debugger;

   array.forEach((arr) => {
     console.log(arr) 
   })
}

reverseArray(sentence)
// Now it works
// RESULT
// sense.
// VM94:7 make
// VM94:7 all
// VM94:7 will
// VM94:7 This
7 months ago · Juan Pablo Isaza
1 answers
Answer question

0

You are modifying your array while iterating through it. Instead You should use copy of it like so:

Array.from(array).forEach((elm) => {
  newArray.push(array.pop())
  console.log(elm)
})

// another variant for old browsers

array.slice().forEach((elm) => {
  newArray.push(array.pop())
  console.log(elm)
})

Or, as you do not need elements in callback, you should use simple for loop

const count = array.length
for (let i=0; i < count i++) {
   newArray.push(array.pop())
   console.log(arr) 
}
7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs