Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

[SugarCube] Sorting Arrays by Values in the Array

edited May 2016 in Help! with 2.0
So I have an array, let's say it's like:
<<set $array = [ [ "Jo" , 3 ] , [ "Sam" , 4 ] , [ "Alex" , 2  ] ] >>

What is the best way to sort that array by the values in the second index of each item? So I'll get "2, 0, 1" or "Alex, Jo, Sam" or similar?

Comments

  • edited May 2016
    note: your example is missing an end square bracket ] at the end of the array definition.

    You can use the Javascript Array sort() method combined with an inline function to do what you want, the method's documentation even includes an example of how to compare numbers.
    To compare numbers instead of strings, the compare function can simply subtract b from a.

    The following is based on your array:
    <<set $array = [["Jo", 3], ["Sam", 4], ["Alex", 2]] >>
    
    before: <<print $array>>
    
    after:  <<print $array.sort(function(a,b){return a[1] - b[1];}) >>
    
    WARNING: The sort method modifies the array it is called on!
  • edited May 2016
    Awesome, thanks so much, greyelf!

    (fixed the end bracket)
Sign In or Register to comment.