简体   繁体   中英

Rearranging Elements For Array of Array

I am trying to rearrange elements in an array of arrays but have been unsucessful. Can anyone offer suggestions? Here are two options I have tried. I want to swap/switch places for the first and second elements.

arr1 is an array of arrays (ie arr[][]) so I created arr2 to be an updated arr1

var arr2 = [];

for (var n = 0; n <arr1.length; n++){
  arr2[n][0] = arr1[n][1];
  arr2[n][1] = arr1[n][0];

}

The other thing I tried was:

function order(arr[]){
  return [arr[n][1],arr[n][0], arr[n][2], arr[n][3]];
}

var arr2 = order(arr1);

You also need to create a new array for each item:

var arr2 = [];
for(var n = 0; n < arr1.length; n++) {
  arr2[n] = [arr1[n][1], arr1[n][0]];
}

The first example you need to use a temporary variable for the switch:

var arr2 = [];

for (var n = 0; n <arr1.length; n++){
  var tempVal = arr1[n][1];
  arr2[n][1] = arr1[n][0];
  arr2[n][0] = tempArr;
}

The second example, in JS the variable shouldn't have brackets next to it, as it's just a loosely typed variable name.

function order(arr){
  return [arr[n][1],arr[n][0], arr[n][2], arr[n][3], arr[n][4]];
}

var arr2 = order(arr1);

Next time, before asking you should check the console. The stackoverflow wiki page on JS has lots of great resources for learning to debug JS.

it's quite easy:

var a = arr1[n][0];
arr2[n][0] = arr1[n][1];
arr2[n][1] = a;

you need to save the first value as a variable, because if you do as you did(arr2[n][0] = arr1[n][1];), your two array indexes will have the same value.

You did:

a = 1, b = 2;
a = b;
b = a;

Which resolves in a = 2, b = 2

Also, your code as it is now, doesn't work. You need to create a new array for the simulation of multidimensional arrays in javascript.

for(i = 0; i < (yourdesiredamountofarrays); i++)
{
    yourarray[i] = new Array();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM