Swapping 2 elements of 2D array

Viewed 65

I am unable to sort the array based on column values. I have a 2-dimensional array:

var cl12 =  [[9, 10.5], [10, 11.5], [12, 13.5], [12.5, 14.5], [14.5, 15], [16, 18], [16, 17]]

Now as you can see in the above array, last and second last elements have same values for 0th index, but they are not sorted based on column since [16,18] should come after [16,17]...now I have written a for loop as below to get a complete sorted array,

 for(i=0;i<cl12.length;i++){
      if((cl12[i][0]==cl12[i+1][0]) && (cl12[i][1]>cl12[i+1][1])){
         var temp = cl12[i+1];
         cl12[i+1]=cl12[i];
         cl12[i] = temp ;
         }
       }  
     console.log(cl12)

but it is giving an error on console : Uncaught TypeError: Cannot read property '0' of undefined"

1 Answers

You are comparing each element to the element at an index one greater, so you should only be looping up to one less than the array's length.

for(i=0;i<cl12.length-1;i++){

var cl12 =  [[9, 10.5], [10, 11.5], [12, 13.5], [12.5, 14.5], [14.5, 15], [16, 18], [16, 17]]
for(i=0;i<cl12.length-1;i++){
  if((cl12[i][0]==cl12[i+1][0]) && (cl12[i][1]>cl12[i+1][1])){
    var temp = cl12[i+1];
    cl12[i+1]=cl12[i];
    cl12[i] = temp ;
  }
}  
console.log(cl12)

Related