Skip to content
Advertisement

How to turn around the content of an array to another array with a forEach-Loop?

I would like to know whats wrong with my code. As in the title descripted I would like to turn around the content of an array with a for loop to another array. I would like to use ES5 for this since I am not used to ES6+ yet.

Here is my code:

    var arrayA = ["h","e","l","l","o"];
    var arrayB = [];
     function copyArray(oldArray, newArray) {
       oldArray.forEach(function() {
            var storeElement = oldArray.pop();
           newArray.push(storeElement); 
     });
       console.log(oldArray + " old array");
       console.log(newArray + " new array");
    }
    
    
    copyArray(arrayA, arrayB);

The result is:

"h,e,l,l old array"
"o new array"
"h,e,l old array"
"o,l new array"
"h,e old array"
"o,l,l new array"
"h,e FINAL old array"
"o,l,l FINAL new array"

But it should be:

"" FINAL old array
"o, l, l, e, h" FINAL new array. 

What is going wrong?

Advertisement

Answer

Ok so Issue is your forEach which not running with oldArray length mean 5 times Why this is happening? It is because you are poping out value withing forEach which change the length and data of forEach.

You can check by putting console.log(oldArray); in forEach.

var arrayA = ["h", "e", "l", "l", "o"];
var arrayB = [];

function copyArray(oldArray, newArray) {
    var length = oldArray.length;
    for (var i = 0; i < length; i++) {
        var storeElement = oldArray.pop();
        newArray.push(storeElement);
    };
    console.log(oldArray + " old array");
    console.log(newArray + " new array");
}


copyArray(arrayA, arrayB);


var reverseArray = ["h", "e", "l", "l", "o"].reverse();

console.log("reverse array");

console.log(reverseArray);
Advertisement