-1

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
Marian07
  • 2,303
  • 4
  • 27
  • 48

1 Answers1

1

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) 
}
BANO notIT
  • 360
  • 1
  • 12