The special function for switching elements within arrays of arrays may yield unpredictable results at certain indexes

Having an Array of Arrays, my Array is named splitarr [Array2[], Array1[], Array0[], Array3[]...]. Unfortunately, it is not ordered correctly from Index Zero to index 2. Therefore, I am seeking a way to rearrange splitarr so that it follows this order => splitarr [Array0[], Array1[], Array2[], Array3[]...]. However, the code I have implemented does not seem to be working as expected. Whenever I attempt to console.log my Array, the indexes where the elements should be switched end up being undefined.

function blabla(){
dividersecond = 2;
splitarrayindex = 0;
splitarr = [[], [], [], []] //this line is just a placeholder, as I already have a functioning array
splitarr = ReorderArray(dividersecond, splitarrayindex, splitarr);
console.log(splitarr);
}

I have a function (which is just a portion of the entire function due to length constraints), in which I call the function responsible for reordering my array.

function ReorderArray(Count, Index, Array){

  var originalIndex = Index;

  for(Index; Index<Count; Index++){
    var swapIndex = (Count-Index);
    var temp = Array[Index];
    Array[Index] = Array[swapIndex];
    Array[swapIndex] = Array[temp];
  }
    return Array();
}

When executed as above, my console output is

[Array(8), undefined, undefined, Array(8), Array(8), Array(8)]

I have also attempted

...
Array[Index] = Array[swapIndex];
Array[swapIndex] = Array[temp];
return Array();
  }
}

Yet, in this case, the console displays something like this.

[Array(8), Array(4), undefined, Array(8), Array(8), Array(8)]

Though I can speculate what might be causing the issue, I am unsure how to rectify it.

It goes without saying that returning my array within the loop makes no sense at all and will only terminate the loop. Nonetheless, it sheds light on what actually occurs during each iteration of the loop.

Despite extensive debugging, I have not been able to reach a definitive conclusion. Thus far, it appears that the value at Array[Index] becomes undefined at its designated position every time the loop is executed.

Hence, the initial loop looks like this

[Array(8), Array(4), undefined, Array(8), Array(8), Array(8)]

and the subsequent loop follows suit with

[Array(8), undefined, undefined, Array(8), Array(8), Array(8)] 

Your assistance in resolving this matter would be greatly appreciated!

Answer №1

You successfully stored the array in a temporary variable.

temp = Array[Index];

However, when you attempt to retrieve it, you are trying to access the position of 'temp' within the 'Array'. This approach will not yield the desired result.

Array[swapIndex] = Array[temp];

I suggest that what you intended was to retrieve the array stored in 'temp'. You can achieve this by:

Array[swapIndex] = temp;

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

Tips for uploading images in Next.js using Firebase

While following a tutorial on Next.js, I encountered an issue with the outdated version of Firebase being used. Despite trying different solutions from the documentation and various sources, I am still facing an error message while attempting to upload ima ...

exploring the possibilities of pairing various data formats using Javascript and Vue

When parsing and mapping two different types of data or objects within i.values, the console output shows: (3) [1, 2, 3,__ob__: Observer] 0:1 1:2 2:3 length:3 __ob__: Observer {value: Array(3), dep: Dep, vmCount: 0} __proto__: Array The next ...

Arranging a group of strings containing negative numbers can lead to surprising outcomes

I have developed a program that calculates the second largest number from a list by converting input into a list. Here is the code: score1 = input() score = score1.split() score.sort() maximum = max(score) count = score.count(maximum) for i in range(0,coun ...

Guide on incorporating Vue components: implementing component 2 within the template of component 1

I'm a Vue beginner and struggling with how to use one component within the template of another or how to combine them in HTML. I've tried looking through the documentation and Stack Overflow but can't seem to figure it out. Currently, I am ...

Dynamic text in Bootstrap 5 Popovers

Having some trouble setting the text on a bootstrap popover: Here's the HTML: <span class="d-inline-block" id="searchPredict" tabindex="0" data-bs-toggle="popover" data-bs-trigger="hover focus" tit ...

Encountering an issue: Unhandled error - Unable to access property 'parentNode' of a null value

I'm attempting to add a new div next to another div using the ComponentID of the first div as a reference. I want to place the second div parallel to the first one, like this: <div> <div id="userActivityStatusMenu-1110">Neighbor 1< ...

Ensuring the checkbox is disabled prior to editing

Check out my table below: https://i.stack.imgur.com/7byIa.png Whenever I click the edit button, I can modify the status field and action field. This feature works correctly. However, the issue is that I am able to change the values of status and action e ...

lowdb only modifies a single piece of information in the JSON file

When updating a JSON file with a lowdb request, only the date gets updated. Upon logging the information to be updated, this is the desired update: res.on("end", function () { let body = Buffer.concat(chunks); let final = JSON.parse ...

Encoding a two-dimensional array into JSON format

In my PHP script, I am querying a database and formatting the results as JSON: $query = mysql_query($sql); $rows = mysql_num_rows($query); $data['course_num']=$rows; $data['course_data'] = array(); while ($fetch = mysql_fetch_assoc($q ...

Finding clarity amidst the chaos of require and export in Express.js (Node.js)

Is there a way to make my socket.io connection modular so that it can run once and be accessible anywhere? How can I export it? var server = require("http").Server(express); var io = require("socket.io")(server); server.listen(5000); io.on('connect ...

What is the way to modify the contents of a div using ajax?

I have blade files in both list and image formats. There are two span buttons here, and I would like to display a list in different formats when each button is clicked. How should I go about writing the code for this? <span id="penpal-image-view" ...

Authorization missing in Select2 Ajax request

Encountering an issue while attempting a get request to a secure endpoint that requires an Auth token. Despite fetching the token asynchronously from chrome.storage, it fails to be included in the ajax request and results in a 401 error ("Authorization hea ...

Carousel-Owl, glide through two items simultaneously

I am currently in the process of developing a slider using the beta version of Owl-Carousel 2, but I am encountering several issues. My goal is to configure the owlCarousel to function as follows: It should scroll through 2 items at a time while displayin ...

Combining Two JSON Arrays Featuring Unique Keys

I have two JSON arrays with slightly different keys. The first JSON array contains the keys id, name, and title. The second JSON array includes id, title, forename, name, and company. I am wondering if it's possible to merge these two arrays so th ...

Update the visibility of an element depending on the current date

I am creating a website for local use on my tablet and I prefer not to use PHP. I have multiple divs that should be shown on different days like this: - div 1 shows today - div 2 shows tomorrow - div 3 shows the day after tomorrow etc... I found some code ...

Inverting array - excluding the initial digit

One challenge I've encountered is with a programming exercise. The task requires inputting numbers and displaying them in reverse order. However, there seems to be an issue where the last entered number is not displayed. #include <iostream> #in ...

Leveraging the power of Express.js, transmit local data alongside a

Why can't I display the active user in my view using plain HTML when console log shows it? Here is the code snippet: app.post('/', function (req, res) { var user = { user : req.body.username }; res.render('doctor_hagfish/pets&ap ...

Encountering an error while trying to install an npm package

$ npm install sillyname npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, wr ...

Javascript is failing to execute promises in sequence

Currently, I am facing an issue with the execution of the code below using promises. The problem lies in the fact that the promise is not executing sequentially; it does not wait for the first block to finish before moving on to the next block. Here is th ...

Adjust the width of menu options using jQuery

One issue I am facing is with the menu on my homepage. I would like the menu options to enlarge upon hover, and while I have achieved this effect, there is a flaw in the animation: When I move my cursor away before the animation completes, the option abru ...