The process of reversing an array is not fully completing due to the pop method being used within a loop

Note: I've been immersed in code for hours now and have reached a stage where I'm starting to doubt the spelling of every word or question if I have dyslexia. Despite this, I know this should be a simple question.

I want to create a basic function (without relying on the standard JavaScript reverse method) that, when given an array, generates a new array with the same values but in reverse order.

Why does the current function remove "C" and "B", but not "A"?

function reverseArray(arr) {
    var reversedArr = [];
    for (var i = 0; i < arr.length; i++) {
        var popped = arr.pop(i);
        reversedArr.push(popped);
    }
    return reversedArr;
}

console.log(reverseArray(["A", "B", "C"]));

Even though the expected outcome is ["C", "B", "A"], it's actually showing only → ["C", "B"]. When I check the array within the function, "A" is still present.

To solve this, I've included

reversedArr.push(arr.pop(arr[0]));
after the for loop and before the return statement. This resolves the issue, but considering that the for loop should continue while i is less than the array length and when the array only contains "A", where the length is 1 and i is 0, shouldn't it also remove "A"?

What am I overlooking here?

Answer №1

Removing an element from an array using the pop method will permanently delete the item and adjust the length of the array. More information can be found here

In your code, it is recommended to use:

var removedItem = arr[i];

And implement reverse iteration as shown below:

for (var i = arr.length - 1; i >= 0; i--)

Answer №2

Give this a shot,

function reverseArray(arr) {
  var reversedArr = [];
  while (arr.length > 0) {
    reversedArr.push(arr.pop())
  }
  return reversedArr;
}

What is the logic behind this?

pop removes the last element in the array without needing an index. Simply keep popping elements until the array is empty.

Answer №3

Solution implemented with the pop method.

function reverseArray(arr) {
    var loopNumber = arr.length 
    var reversedArr = [];
    for (var i = 0; i < loopNumber; i++) {
        var popped = arr.pop();
        reversedArr.push(popped);
    }
    return reversedArr;
}

console.log(reverseArray(arr));

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

I am experiencing an issue where tapping on the Status Bar in MobileSafari is not functioning correctly on a specific

I am struggling to troubleshoot this problem with no success so far. The HTML5 JavaScript library I'm developing has a test page that can display a large amount of output by piping console.log and exceptions into the DOM for easy inspection on mobile ...

What steps should I take to create a plugin for a library if defining it as a peerDependency does not provide a specific implementation for me to work with?

Requirements for My Plugin: I'm currently in the process of developing a new plugin that is dependent on popularLibrary.js. Here are the key points about my plugin: It will not function properly if popularLibrary.js is missing. It is designed to wo ...

Transforming iframe programming into jquery scripting

Currently, I have implemented an Iframe loading the contents within every 5 seconds. It works well, however, there is a consistent blinking effect each time it loads which can be quite bothersome. I am looking to replace the iframe with a scrolling div so ...

How to dynamically add variables to object paths using JavaScript and Angular

I've been struggling to grasp this concept, despite hours of searching. My goal is to dynamically generate form fields based on a user-selected 'type' from a dropdown menu. This will be linked to the variable "currentType" in Angular, which ...

Employing the findOne method repeatedly in a loop can significantly slow down operations in Node.js

Currently, I am working on a project using Node.js in conjunction with MongoDB, specifically utilizing Monk for database access. The code snippet I have is as follows: console.time("start"); collection.findOne({name: "jason"}, function(err, document) { ...

fade in and out twice (for beginners)

Jquery <script> //Code snippet $(document).ready(function(){ $(".team").click(function(){ $(".panel").fadeToggle("3000"); }); $(".team").click(function(){ $(".teamh").fadeToggle("3000"); }); }); </script> HTM ...

Tips for enabling both vertical and horizontal scrolling using the mousewheel on a webpage

Our website features a unique scrolling functionality where it starts off vertically and then switches to horizontal once the user reaches the bottom. This allows for a seamless transition between scrolling directions. In addition, users can easily naviga ...

Exporting a module with Node.js is a crucial aspect of building

Within my custom module, I have successfully set up an export function. module.exports = function(callback) { var request = require("request") var url = "http://sheetsu.com/apis/94dc0db4" request({ url: url, json: true }, ...

Error: The database has encountered a duplication error in the followers index of the MERNSM.users collection, with a duplicate key value of undefined

Encountered a MongoServerError: E11000 duplicate key error collection: MERNSM.users index: followers_1 dup key: { followers: undefined }. This is puzzling as there is no unique constraint set in my schema. I am unsure of what could be causing this issue, e ...

Display a single item using Jquery when clicking on an element with the same class

I'm relatively new to JQuery/Javascript scripting and I'm having some difficulty. How can I display one item with the same class without affecting the other items? Here is my code: $(function() { $('.embedContainer > .myPosterImage& ...

Incorporating dynamic numerical values into image names within a Vue JS application

I have linked an image with the following code <img title="head" :src="availableParts.heads[selectNextHeadIndex].src"/> This image is called from a JSON file: { id: 1, description: 'A robot head with an ...

Adjust the sliders according to the current time

I am looking to display different sliders based on the time of day. For instance, 'slider set 1' from 0-9am, 'slider set 2' from 9am-12pm, and so forth. I am new to java script and need assistance in solving this challenge. Below is the ...

Can the functionality of a button be disabled after being clicked a total of 5 times?

Once a user clicks the button five times, I plan for it to be disabled. Can this be achieved solely with HTML, or would JavaScript be necessary? ...

The proper way to insert data in JavaScript and PHP

Hello. I have a new function to add a row in my form. However, I recently added a second input field and I am unsure of how to correctly insert it. Below is my JavaScript code: <script type="text/javascript" src="jquery.js"></script> <scri ...

Identifying Mistakes during Promise Initialization

Looking for a more efficient way to work with Bluebird promises Promise.resolve() .then(function() {return new MyObject(data)}) .then.....etc .catch(function (e){ //handle it}) I am dealing with MyObject and data coming from an external sourc ...

The Typescript compiler is unable to locate the module './lib'

I'm currently integrating the winston-aws-cloudwatch library into my TypeScript server-side application. If you want to replicate the issue, I have provided a SSCCE setup on GitHub. Here are the details: index.ts import logger from './logger& ...

Updating JSON data in Node.js by adding a new object

I'm facing a situation where I have a JSON file acting as a database to manage users by adding, removing, and modifying them. Currently, I have the following code snippet: 'use strict'; const fs = require('fs'); let student = { ...

Ways to retrieve the text value of the first column using a button click event in JavaScript

As a beginner in HTML and JavaScript, I have a clear code provided below: HTML <tr> <td>1</td> <td>Info1</td> <td><input class="btn" value="Show" onclick="showTdSecond();" type="button"></td> & ...

What sets apart express.Router() from using multiple express() objects?

When utilizing the latest express 4 router, it becomes possible to organize various route paths into separate files like the following example: // Inside cars.js const router = express.Router(); router.get('/brands', function(req, res) { ... } ...

Unable to properly connect my CSS file to the header partial

I am struggling to include my CSS file in the header partial Here is the link I am using: <link rel="stylesheet" href="stylesheets/app.css"> This is what my directory structure looks like: project models node_modules public stylesh ...