Inverting Arrays Recursively with JavaScript

Currently, we are delving into functional JavaScript in my programming course with a particular assignment. However, I seem to be struggling to make the code work as intended. I would greatly appreciate any advice on how to improve this piece of code. Everything except for the body was provided for me to utilize. Here is what I have managed to come up with so far: (Unfortunately, it seems to only return the content of the first array index instead of reversing all of them. I attempted changing it to

 if(arr.length <= 1) return arr;

however, that adjustment never triggers the base case.)

function ReverseArray(arr) {

//base case

if(arr.length == 1)
{
   return arr[0];
}
if(arr.length == 0)
{
   return 0;
}

var head = arr.pop;
var newArr = [head, ReverseArray(arr)];
return newArr;
}

Answer №1

a = b <--assignment
c == b <-- comparison 

Examining your script:

if(list.size = 5) 

must be revised to

if(list.size == 5)

similarly for the zero check


ALSO, don't forget to use the pop function

var top = list.pop;

make sure to add parentheses as follows

var top = list.pop();

Answer №2

If you're looking for a concise and efficient solution, using the ternary operator in a single line is the way to go.

function reverseArray(arr) {
  return arr.length < 2 ? arr : [arr.pop()].concat(reverseArray(arr));
}
console.log(reverseArray([5, 8, 2, 9]));

Answer №3

Check out this code snippet with a fully functional function example. Just to let you know, there is also an available built-in function that can achieve the same result.

In my opinion, aside from the confusion related to assignment and comparison operators, it seems like when constructing the result array, using the Array.concat() method to combine arrays might have been a better choice instead of creating a new array where the second item was an array itself.

var a = [1,2,3,4,5];
console.log(ReverseArray(a));
    
function ReverseArray(arr) {
    if(arr.length < 2) {
        return arr;
    } else {
        return [arr.pop()].concat(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

The most recent release of Chrome (Version 47.0.2526.80 m) introduces an intriguing feature. When using navigator.webkitGetUserMedia, the returned stream now lacks a

I recently encountered a problem with my code that used to access the camera on Chrome browser and release it after use. Here's the code snippet: Starting the Camera: navigator.webkitGetUserMedia($scope.options.videoObj, function (stream) { $sco ...

Using Sequelize and Express API for verification in the controller is an essential component of building

I'm currently working on building the API for my web app, utilizing Sequelize and Express. I have set up models with Sequelize and am in the process of developing controllers and endpoints. My main query is: Should I perform data validation checks be ...

Retrieve information from the input field and then, upon clicking the submit button, display the data in the

When a user inputs their name, email, subject, text, and telephone number, I want to send an email with that data. The email will be sent to a specific email address, such as [email protected]. This process is crucial for a hotel website, where the em ...

Angular version 8.2 combined with Firebase can result in errors such as those found in the `./src/app/app.module.ngfactory.js` file towards the end of the process when attempting to build with

My first time posing a query on this platform, and certainly not my last. The issue at hand involves the ng-build --prod process failing to complete and throwing errors in my Angular 8.2.14 application. I've integrated Firebase into my project succes ...

What is the best way to pass an object into a method within a select element using Vue

Kindly review the following code snippet. <tr> <td>Select Timeslot</td> <td colspan="2"> <select class="form-control" v-on:change="onTimeSlotClick"> <option v-for="slot of slots"> <l ...

Handling 404 Response from WebAPI in $Http.get() Function

While using my web application, I am executing a GET command to access a remote HTTP WebAPI service. $http.get(url).then(function(data) { do_something(); }); When the WebAPI successfully returns data, everything functions as expected. However, in cases w ...

How can we format a number to match the Brazilian number system while still maintaining its ability to be used in calculations?

Is there a known method to convert the number 123,123,214.93 into Brazilian currency format (123.123.214,93) for display purposes only? I attempted to achieve this conversion using a JavaScript function where I added periods after every 3 numbers and repl ...

How should values be properly stored in a constant using mongoose?

Within my user model, I have included timestamps. I am seeking a way to retrieve the createdAt date and store it in a variable. My initial attempt was: const date = await User.find({ serial: serialId, }).select('-_id createdAt'); The result re ...

What is the best way to analyze the values within two separate arrays for similarities?

Given two non-empty arrays of the same length, calculate and return the score based on the answers provided. Each correct answer earns +4 points, each incorrect answer deducts -1 point, and each blank answer (represented by an empty string) earns 0 points. ...

Unable to choose anything beyond the initial <td> tag containing dynamic content

Struggling to implement an onclick delete function on dynamically selected elements, but consistently encountering the issue of only selecting the first element each time. // Function for deleting entries $("#timesheet").on('click', &ap ...

Having trouble getting a new input box to be added when clicking with AngularJS?

I am facing an issue with adding dynamic form fields to the database using PHP. I have utilized angular for this purpose, but only the last form field is getting inserted into the database. To address this, I attempted using arrays and loops to increment a ...

Uploading videos to a single YouTube channel using the YouTube Data API

I have been tasked with creating a node js app for a select group of individuals who need to upload videos. However, our budget is quite limited and we are unable to afford cloud storage services. I am curious if it would be feasible to create a key syste ...

What is the best way to retrieve an ID from a select multiple using Element?

I am working on a select element for assigning persons to a project. My goal is to send the ID of the selected person object to a specific function. Here is what I have tried so far: <el-form-item label="Assign to:" prop="person"> & ...

Attempted to utilize zipstatic but received no feedback

I attempted to utilize the Zipstatic API with jQuery in my code, as shown below. However, I am not receiving any response. Could there be something missing? jQuery(function() { jQuery("#form").hide(); jQuery("#postcode").keyup(function() { var c ...

Creating a dynamic HTML table in GAS with a radio button in every row poses the challenge of assigning a unique ID to each radio button in each row using a variable name

I am currently working on a Google Apps Script web application that involves a search box and a button. When the button is clicked, it dynamically loads an HTML table based on the user input from the search box. The script then retrieves data from a Google ...

All-in-one Angular script and data housed within a single document

Context I want to design a personalized "dashboard" to assist me in staying organized. This dashboard will help me keep track of the issues I am currently handling, tasks I have delegated, emails awaiting response, and more. While I am aware of project ma ...

What is the most effective way to obtain a customer's latitude and location by prompting them to drop a pin on Google Maps?

My Android app has an API, but on my website I'm wondering how I can retrieve a person's location by having them place a marker on a Google Map. Is there a standard method for this? I need to obtain the latitude and longitude coordinates and send ...

Instead of using a v-if condition, add a condition directly in the Vue attribute

Apologies for the unclear title, as I am unsure of what to name it with regards to my current issue, I am attempting to create a component layout using vuetify grid. I have a clear idea of how to do this conventionally, like so: <template> <v-fl ...

What is the best way to retrieve the initial element from a map containing certain data?

I am attempting to retrieve the first image path directory from an API that contains an Image so I can assign the value to the Image source and display the initial image. However, when using fl[0], all values are returned. Below is the code snippet: {useL ...

Utilizing a promise instead of making a jQuery ajax request

A scenario I am facing involves a function that is set to execute jquery.ajax and return it as a promise for future processing. However, in certain cases, the function possesses enough information to proceed synchronously without triggering the ajax call. ...