What is causing this foreach loop to not remove all of the elements?

Why is it only popping twice instead of 4 times?

I attempted a for-of loop but still got the same result. https://i.sstatic.net/48ZQ4.jpg

var arr = [1, 2, 3, 4];
arr.forEach((val, index, io) => console.log(val, index, io.pop()))

Answer №1

Your script is functioning as anticipated.

Array.pop() method eliminates the last item from an array and gives back that item. This process alters the original array.

The Array.pop() operation returns the extracted element from the array.

If the iteration index starts at 0, it will iterate over the array [1, 2, 3, 4], removing 4 during the first iteration, thereby reducing the length of the array to 3.

If the iteration index begins at 1, the loop processes the Array [1, 2, 3] and removes 3 from it.

At this point, the Array has a length of 2 after two completed iterations, causing the loop to terminate.

This explains why your loop only runs twice.

const arr = [1, 2, 3, 4];
arr.forEach((val, index, io) => {
  console.log(`Iterating ${index + 1}`);
  console.log(val, index, io.pop());
  console.log(`Array After Iteration ${io}`);
});
console.log(`Final Array ${arr}`);

Answer №2

let numbers = [1, 2, 3, 4];
numbers.forEach((num, index, arr) => console.log(num, index, arr.pop()))

Your code is functioning as expected

num  |  index  |  arr.pop() | Modified Array
1        0          4         [1, 2, 3]
2        1          3         [1, 2]
// Since the last element reached is 2, no further iteration is necessary and the loop stops.

With each log statement, the last element of the array is removed and the loop progresses.

The callback operates only on the current elements in the array, resulting in the removal of elements during logging, leading to only two iterations being executed.

I hope this explanation helps clarify things! ✌

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Suggestions on coloring polyline segments according to the density of neighboring segments surrounding the specific polyline segment

Apologies for the lengthy title, but I am interested in developing a polyline heatmap that changes color based on the number of lines within a certain proximity. Here is an example of what I have in mind: https://i.sstatic.net/W2lox.jpg Are there any inn ...

When the button is clicked in CSS and JSP, a disappearing div is instantly replaced by a new div

I am brand new to Web programming. I have just grasped the concepts of HTML and CSS, but Java Script is still a mystery to me. The scenario I am facing is as follows - there are two buttons and two divs. When one button is clicked, the corresponding div a ...

Create a PDF document using pdfmake within an iframe element

I am using this JS code and would like to generate a PDF within an iframe tag using pdfmake library. function start(){ var docDefinition = { content: [ { table: { multiple pages headerRows: 1, widths: [ '*&apos ...

Implementing the 'bootstrap tour' feature in a Ruby on Rails application

I have integrated bootstrap-tour.min.css and bootstrap-tour.min.js into my project. <script type="text/javascript" src='bootstrap-tour.min.js'></script> <link rel="stylesheet" type="text/css" href="bootstrap-tour.min.css"> Her ...

NextAuth encountered a CLIENT_FETCH_ERROR error while processing the session callback

Encountering issues while trying to set up nextauth v4. Keep getting this error: Client fetch error, Unexpected end of JSON input {error: {…}, path: 'session', message: 'JSON.parse: unexpected end of data at line 1 column 1 of the JSON d ...

innovative speedometer javascript or jquery extension

Looking for a plugin that can dynamically display a speedometer using AJAX. One suggestion is to set a background and rotate the needle. Does anyone know of a plugin that can accomplish this? ...

What is the best way to extract data from a JSON object using JavaScript, Node.js, or React?

The data received from the server includes information on two different products: [{ "model": "G7", "brand": "LG", "price": 999.99, "image": "https://www.bell.ca/Mobility/Products/LG-G7-ThinQ?INT=MOB_mobdevpg_BTN_poplink_Mass_051016_mb_details#", ...

Ways to verify the nodemon version that is currently installed on your local machine

On my Windows 10 machine, I recently installed nodemon locally in a project and now I'm curious to know which version is installed. Can someone please share the command to check the version of nodemon without needing to install it globally? My aim is ...

Unable to load the JSON texture file

I recently exported a 3D model to JS from Blender, but I'm encountering an issue with the texture not showing up properly. Even when I remove the texture file, the browser generates an error saying that 'map.png' cannot be found. This indica ...

Initiating a YouTube video with a click on its thumbnail image - a jQuery tutorial

I am currently working on code that successfully displays YouTube videos. However, I would like the video to start playing when the cover image is clicked. How can I achieve this functionality? Thank you for your help! <div id="video" style="display: ...

Retrieving properties from a URL pathname using React.js

Struggling to retrieve the uid and token from the URL pathname in my React application using the match method. However, encountered an error: Uncaught TypeError: n is undefined Here's the snippet of the code: const ResetPasswordConfirm = ( {match, ...

Apply a class to an element as it comes into view 100 pixels before scrolling past it

I need help adding a specific class to an element (class abc) when it is 100px below the top of the viewport. Currently, the class is being added to all divs instead of individual elements. Any advice on how to fix this? $(function() { $(document).scr ...

What is the best way to transfer the userId from the browser to protractor?

Using *ngFor in my angular2 component to render users has been successful. <ul> <li *ng-for="let user of users"> <input [(ng-model)]="user.name"> <button (click)="remove(user._id)">Remove</button> ...

Transferring Arrays from PHP Script to JavaScript Script

Can someone help me figure out how to pass an array from my PHP file to a JavaScript file? Here is the array I have: $pictures = array( "1" => array("caption" => "1920x1200px", "tag" => "wallpaper", "link" => "#"), ); In my JavaScript file, I ...

Retrieving information in JSON format

My goal is to retrieve data from the info.php file in order to utilize it in my project. This is what the content of info.php looks like: <?php $dbh = new PDO('mysql:host=localhost;dbname=csgo', 'root', ''); $sth = $dbh ...

Replicate the functionality of a mouse scrolling event

I have incorporated Jack Moore's Wheelzoom jQuery plugin to zoom and drag an SVG image on my website. However, I also want to include manual zoom in and out buttons for the users. I am considering two options to achieve this - triggering a mouse whe ...

Google Maps integrated AWS server

While utilizing an AWS server for my application, I have encountered a difficulty with Google Maps. When running my application using localhost, Google Maps functions perfectly fine. However, when attempting to run the application using an IP address, it f ...

Incorrect port being used for fetching URL in redux.js

I have developed a MERN application that utilizes both async/await with Axios and Redux to handle the data flow within the application. Redux is primarily used for login and authorization, as shown in this tutorial. While some shared tables are fetched thr ...

Issue with Struts 2 tag causing malfunction in validating the collection

When iterating through a list in a JSP file using Struts 2 tags, the code below is used: <%@ taglib prefix="s" uri="/struts-tags"%> <head> ... The issue arises with date validation. The following line of code does not work: <td><s:d ...