Looking to develop a method that extracts a value from an array, saves it, and transfers it to another array exclusively through the use of .pop and .push methods

I'm currently working on an assignment for my JS course that involves creating a function using only .push and .pop commands. The task is to take the last value from the first array and move it to the second array. Unfortunately, I seem to be messing something up in my code.

Here's the example we were given to follow:

let anArray = [1, 2];
let anotherArray = [3, 4];

move(anArray, anotherArray);

anArray //should be [1]
anotherArray //should be [3,4,2]

And here's what I've attempted so far:

function move(parameter1, parameter2){
    var anArray = [1, 2];
    var anotherArray = [3, 4];
    var storage = anArray.pop();
    anotherArray.push(storage);
}

I'm seeking some guidance as to why my function doesn't seem to be working as expected. I'm fairly new to JavaScript, so any help would be greatly appreciated.

Thank you,

Luis.

Answer №1

Your function parameters were unused, instead, you created new variables. Here's a corrected example:

function swap(arr1, arr2) {
  var temp = arr1.pop();
  arr2.push(temp);
}
let myArray = [1, 2];
let yourArray = [3, 4];

swap(myArray, yourArray)
console.log(myArray)
console.log(yourArray)

Answer №2

One reason for the confusion is that in the function move, you redefined anArray and anotherArray. The scope of the outer arrays is different from the variables defined inside the function. The actual movement of elements is happening within the arrays defined inside the method. The confusion arises from using the same names for both sets of arrays.

Below is the implementation you have created, which is functional but not based on the parameters passed:

function move(parameter, parameter2) {
  var anArray = [1, 2];
  var anotherArray = [3, 4];
  var storage = anArray.pop();
  anotherArray.push(storage);
  console.log(anArray)
  console.log(anotherArray)
}

move([],[])

In order to make your function work with the input parameters passed, you can make the following changes:

function move(parameter, parameter2) {
  const storage = parameter.pop();
  parameter2.push(storage);
}

let anArray = [1, 2];
let anotherArray = [3, 4];

move(anArray, anotherArray)
console.log(anArray)
console.log(anotherArray)

I hope this explanation is helpful to you.

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

The issue arises when trying to use data provided by a service, resulting in an "undefined

Looking to create a handler that generates an array of categories based on the presence of "categories" for a specific "resource". However, encountering an error with the last method. ERROR TypeError: "this.allProjectResources is undefined" import { Res ...

What is the correct way to utilize "data:" in a jQuery AJAX call?

There seems to be an issue with my code within the deletePost function. The problem lies in the fact that $_GET['title'] is empty. Although I set the title value in the ajax using postTitle: $(this).siblings("h3.blog").text(), it doesn't see ...

The term "Highcharts does not exist"

I'm encountering an issue with my code: <html> <head> <title><%=sAtaskaitaTitle%></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name=vs_targetSchem ...

Using the DatePicker component with non-escaped Latin alphabet characters in date-fns for ReactJS

While attempting to integrate the DatePicker component from Material UI into my React project, I encountered an error. Although many attributed the issue to a version discrepancy, what ultimately resolved the problem for me was assigning a value to the Da ...

Error in line 36: firebase.auth function is undefined

Snippet of index.html code <html> <head> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" ...

JS filter function is not functioning as expected. It's unclear what the issue might be

Check out my previous inquiry What could be the issue with my filter? I've implemented a filter, but it seems to have some glitches when dealing with specific values. The 'No Record Found' message doesn't appear as expected in certain ...

CSS compatibility across different browsers

Check out my jsFiddle for an example of an onHover event that changes the image. It's working perfectly in chrome, but not quite right in firefox. Any suggestions on how to fix it? Here's the jQuery function I'm using: $(document).ready(fu ...

history.js - failure to save the first page in browsing history

I have implemented the history.js library to enable backward and forward browser navigation on an AJAX products page triggered by clicking on product categories. While I have managed to get this functionality working smoothly, I am facing a particular iss ...

At times, the loading image fails to appear on Ajax

Take a look at my code below: function apply_image_effect(){ $.ajax({ url: "image/image.php", global: false, type: "POST", data: ({my_color:encodeURIComponent($('#my_color').val()),my_size:$('#my_size&apos ...

An error popped up: "argument list is missing) after"

Encountered an issue: Error message: missing ) after the argument list $('.next-btn').append("<a class="actionsubmit" ng-click="onSubmit('hello.html')">Check</a>"); ...

The trim() method in Vue.JS does not properly handle trimming a passed string

I've been attempting to eliminate white space from a property of one of the returned objects using the .trim() function, but it's not working as expected. Even after trying JavaScript functions like .replace(/\s/g,''), the issue p ...

Rotating an image by 90 degrees in C programming involves a specific set of steps

Trying to convert an image to black and white, then rotate it 90 degrees in C as a newcomer to programming. Here's what I've done so far: #include<stdio.h> #include<string.h> int main () { FILE* first; FILE* second; FILE* third; int ...

ESLint flagging "Unexpected tab character" error with "tab" indentation rule enabled

Currently, my ESLint setup includes the Airbnb plugin (eslint-config-airbnb) along with the Babel parser. I recently decided to enforce the rule of using Tab characters for indentation instead of spaces. This is how my .eslintrc file looks like: { "p ...

Utilize Vue.js to transmit HTTP requests with specified headers and parameters

I'm trying to figure out how to create a LinkedIn login component, but I'm having trouble finding information about headers and parameters. Can someone help me understand how to send a GET or POST request with parameters and headers? Here's ...

Angular 2 template can randomly display elements by shuffling the object of objects

I am working with a collection of objects that have the following structure: https://i.stack.imgur.com/ej63v.png To display all images in my template, I am using Object.keys Within the component: this.objectKeys = Object.keys; In the template: <ul ...

An error was encountered stating "TypeError: Unable to call function on undefined object while attempting to utilize a JSON object

My current setup involves using D3js with MongoDB and AngularJS to showcase my data. Everything works smoothly until I decide to give my JSON array a name. Suddenly, Angular starts throwing errors at me and I'm left confused as to why. Here is the or ...

Animated jQuery carousel with a timer countdown feature

Currently, I am developing a jquery slider/carousel to display various promotions. I am seeking a method to indicate the time left until the next promotion appears. Similar to the flash promo on this website: Do you have any suggestions? ...

Modify the appearance of a nested div using CSS hover on the main JSX container

Within the material-ui table component, I am dynamically mapping rows and columns. The className is set to clickableRow. The TableRow also includes a hover options div on the right side: const generateTableHoverOptions = () => { if (selected) { ...

loop through the array of objects using ng-repeat in Angular

I am facing an issue where I need to display the data fetched from a service in my application. The service response is as follows: Object {resultado:array[2], mensaje: "4 personas `necesita tu ayuda"} Currently, the "resultado" field contains an object ...

What do you notice about interactions involving 'input type=text' in HTML and JavaScript?

When a new binding is created for the value property on an input, any manual modifications by the user no longer update the value. What happens when the binding is altered? Does regular user interaction involve key press listeners? I've modified the ...