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

foreach loop javascript
javascript foreach object
javascript loop through array of objects
foreach php
foreach arrow function
jquery array foreach
foreach array push javascript
foreach loop w3schools

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);

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);

Array.prototype.forEach(), the value of the element; the index of the element; the Array object being forEach() executes the callback function once for each array element; There is no way to stop or break a forEach() loop other than by Kindly make sure you are aware of the implications while using About · Contact Us · Firefox. Using foreach with arrays (C# Programming Guide) 05/23/2018; 2 minutes to read +4; In this article. The foreach statement provides a simple, clean way to iterate through the elements of an array. For single-dimensional arrays, the foreach statement processes elements in increasing index order, starting with index 0 and ending with index Length - 1:


When you are doing the pop, is over a new copy of your array, you are not modify the oldArray.

Using JavaScript forEach to do Array Looping and Iterations , About the Author: DJ Rosenbaum forEach() method to loop through arrays with some examples. Let's take a look at some parameters passed into the forEach​() callback forEach is great for looping over an array of values to run a function on each value. Strategic partner, not just another vendor. 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 sinc


You are changing the array while iterates it, because that you get this kind response.

To do this you can do in this way

var arrayA = ["h","e","l","l","o"];
var arrayB = [];
function copyArray(oldArray, newArray) {
  newArray = oldArray.reverse().slice();
  oldArray.length = 0;
  console.log(oldArray + " old array");
  console.log(newArray + " new array");
}


copyArray(arrayA, arrayB);

The two ways of iterating through arrays: list(), each(), and foreach , The second way to use foreach does allow you to extract keys, and looks like this: Another commonly used way to loop over arrays is using the list() and each() All arrays have a cursor, and you can freely move it around - it is used in the is "​get the current element in the array, and assign its key to $var and its value to  How to merge array in one array under foreach loop. I have array i want to merge under foreach loop please provide sollution how can i do it. This content


What you've encountered here is looping through an array while editing its contents.

For every element in the old array you pop an element and push it onto another element. Think about what happens when the forEach loop is on the nth element of the array and the n+1 th element is popped? It's now looping over an array that is one element shorter than before? Which element then becomes next in the forEach loop?

If you are wanting to remove all the elements in the first array use a while

while(oldArray.length !== 0){
    newArrary.push(oldArray.pop());
}

If you are wanting to preserve the original array loop over each element and add it to the new array

oldArray.forEach(function(oldArrayElement) {
    newArray.push(oldArrayElement);
});

How to remove an array element in a foreach loop?, Which One is Most Demanding Back-End Web Framework between Laravel , NodeJS Multidimensional Associative Array in PHP · How to make a spider-bot in PHP ? Use unset() function to remove array elements in a foreach loop. user defined function then it unsets the value associated with the variables inside it,  Two arrays in foreach loop one containing the country codes and another containing You should try this for the putting 2 array in singlr foreach loop


As pointed out you can use reverse. But to answer you question about why this doesn't work: You are modifying the array in place so the forEach loop exits early.

So one solution would to be:

  1. Don't modify the array you are looping through
  2. Get the last item from the oldArray and add it to the newArray
  3. Then the second-last item from oldArra and add it to the newArray

etc.

We know that we can get the last item from array with

var lastItem = myArray[myArray.length-1]

So to get the second last item we would do

var secondLastItem = myArray[myArray.length-2]

We can still use the forEach method, since the callback has few parameters like the curent item and the current index.

So when you loop through an array the first index is 0, next time the index becomes 1, etc.

Now we have something that increases as our loops continues and we can subtract 1 , then subtract 2, then subtract 3, etc.

So our solution could look like this;

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

copyArray(arrayA, arrayB);

Iterate associative array using foreach loop in PHP, (2D) array in PHP ? Which One is Most Demanding Back-End Web Framework between Laravel , NodeJS and Django ? How to make a spider-bot in PHP ? Both arrays can combine into a single array using a foreach loop. Array: Arrays Example 2: This example uses array to display its index with value. filter_none. How to copy array element from one array to another C# array. Array Index Array rank Array foreach loop Array ForEach Action Array lowerbound and upperbound


foreach - Manual, The foreach construct provides an easy way to iterate over arrays. foreach works only Reference of a $value and the last array element remain even after the foreach loop. But it also sees that you want to look at all VALUES by reference (​&$val), I want to add some inline comments to dtowell's piece of code about the​  Store values from foreach loop into array. GitHub Gist: instantly share code, notes, and snippets. Skip to content. You signed in with another tab or window.


6.3. Enhanced For-Loop (For-Each) for Arrays, _images/appinvForEachComparison.png System.out.println( value ); } // for each loop with a String array to print each name // the type for variable name is String! for Add another high score and another name to the arrays and run again. Run Change the loop to an indexed for loop to make it change the array values. In this program, foreach loop is used to traverse through a collection. Traversing a collection is similar to traversing through an array. The first element of collection is selected on the first iteration, second element on second iteration and so on till the last element. Previous Tutorial: C# switch Statement.


Using foreach with arrays, However, with multidimensional arrays, using a nested for loop gives you more control over the order in which to process the array elements. See  See if you can turn that into a more generic loop. The rotated index goes from 0 to length of array-1. The x index goes from 2 however much you rotate (this time 2) and wraps around. I hope that made sense. Now look at clockwise.