Skip to content
Advertisement

Function which is swapping Elements in an Array of Arrays, returns undefined at the specific Indexes

I have an Array of Arrays. My Array is called splitarr[Array2[],Array1[],Array0[],Array3[]…]. It is not ordered correctly from Index Zero to index 2. So I want to swap splitarr that it looks more like this => splitarr[Array0[],Array1[],Array2[],Array3[]…]. However my code does not seem to work. When i try to console.log my Array, the indexes where the elements are supposed to be switched are undefined.

function blabla(){
dividersecond = 2;
splitarrayindex = 0;
splitarr = [[],[],[],[]] //this is just pseudo code line, i already heave a functioning array
splitarr = ReorderArray(dividersecond,splitarrayindex,splitarr);
console.log(splitarr);
}

I have a function (this is just one section of the function because everything else would be too long), where i try to call the function that reorders 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();
}

if i do it like this my console returns

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

I’ve also tried this.

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

But then the console will return something like this.

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

I can imagine what is wrong, however I am not so sure and I don’t know how to fix this.

Returning my array in the loop makes of no sense at all of course, it will just end the loop, but this shows what is actually happing during each run of the loop.

I have debugged a lot and i can not come to any conclusion. so far, the value at Array[Index] seem to turn undefined at the position its being placed at whenever the loop is being called.

So the first loop looks like this

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

and the second loop like that

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

Would be happy if I’d get some help!

Advertisement

Answer

You have stored correctly the array in temp variable

temp = Array[Index];

But when you are trying to recover it, you are trying to access the postion ‘temp’ from the ‘Array’. This won’t work.

Array[swapIndex] = Array[temp];

I believe that what you wanted was to recover the array, stored in ‘temp’. Like this:

Array[swapIndex] = temp;
Advertisement