Sort a complex array of arrays by value inside

I have an array of arrays in javascript configured inside an object that I am storing in local storage. These are the high scores for Phonegap in the format {'0':[[score,time],[score,time]} , where 0 is a category. I can see the ratings with a[1][0] . First I want to sort the results with a high rating.

 var c={'0':[[100,11],[150,12]}; c.sort(function(){ x=a[0]; y=b[0]; return yx; } 

However, b [0] always gives an undefined error.

I am new to Javascript and this is my first major test as a learning experience. Although I looked at a few examples in stackoverflow, I still can't figure out what it is.

+4
source share
2 answers

You need to declare the parameters of the comparator function.

 c.sort(function(){ 

it should be

 c.sort(function(a, b){ 

and you need to call sort in the array as "am not i am", so

 var c={'0':[[100,11],[150,12]]}; c[0].sort(function(a, b){ var x=a[0]; var y=b[0]; return yx; }); 

leaves c in the following state:

 { "0": [ [150, 12], [100, 11] ] } 
+7
source
 function largestOfFour(arr) { for(var x = 0; x < arr.length; x++){ arr[x] = arr[x].sort(function(a,b){ return b - a; }); } return arr; } largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]); 
0
source

Source: https://habr.com/ru/post/1396893/


All Articles